python中如何去除列表中重复元素?

方法一:

用内置函数set:

 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
list2 = list(set(list1))
print(list2)

方法二:

遍历去除重复

 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
list2=[]
for i in list1:
if not i in list2:
list2.append(i)
print(list2)

列表推导式

 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
list2=[]
[list2.append(i) for i in list1 if not i in list2]
上一篇:浅谈_依赖注入 asp.net core


下一篇:PHP绘制验证码