在Python中,删除列表中的重复素可以通过以下几种方法实现:
1. 使用集合(set):
lst = [1, 2, 3, 3, 4, 5, 5, 6]
lst = list(set(lst))
print(lst) 输出:[1, 2, 3, 4, 5, 6]
2. 使用列表推导式:
lst = [1, 2, 3, 3, 4, 5, 5, 6]
new_lst = []
[new_lst.append(x) for x in lst if x not in new_lst]
print(new_lst) 输出:[1, 2, 3, 4, 5, 6]
3. 使用字典(dict.fromkeys):
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist) 输出:['a', 'b', 'c']
4. 使用排序和遍历:
def deleteDuplicatedElementFromList(lst):
lst.sort()
length = len(lst)
lastItem = lst[length - 1]
for i in range(length - 2, -1, -1):
currentItem = lst[i]
if currentItem == lastItem:
lst.remove(currentItem)
else:
lastItem = currentItem
return lst
listA = ['python', '语', '言', '是', '一', '门', '动', '态', '语', '言']
print(deleteDuplicatedElementFromList(listA)) 输出:['python', '语', '言', '是', '一', '门', '动', '态']
5. 使用列表理解式:
l1 = ['b', 'c', 'd', 'b', 'c', 'a', 'a']
l2 = []
[l2.append(i) for i in l1 if not i in l2]
print(l2) 输出:['b', 'c', 'd', 'a']
以上方法各有优缺点,选择哪一种取决于你的具体需求和应用场景。需要注意的是,使用集合去重会丢失原始列表的顺序,如果需要保持顺序,可以使用排序加遍历的方法或者列表推导式
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/140403.html