python - list去重

1. 遍历列表

lst = [3, 4, 5, 1, 6, 2, 7, 3, 1, 2]
new_lst = []
for i in lst:
  if i not in new_lst:
    new_lst.append(i)

>>> print new_lst
[3, 4, 5, 1, 6, 2, 7]

先建立一个新的空列表,通过遍历原来的列表,再利用逻辑关系not in 来去重。
总结:这样可以做出来,但是过程不够简单。但是此方法保证了列表的顺序性

2.利用set的自动去重

lst = [3, 4, 5, 1, 6, 2, 7, 3, 1, 2]
new_lst = list(set(lst))

>>> print new_lst
[1, 2, 3, 4, 5, 6, 7]

将列表转化为set集合再转化为列表,利用set集合的自动去重功能。简单快速。缺点是:使用set方法无法保证去重后的顺序

但是,可以通过列表中索引(index)的方法保证去重后的顺序不变

lst = [3, 4, 5, 1, 6, 2, 7, 3, 1, 2]
new_lst = list(set(lst))
new_lst.sort(key=lst.index)

>>> print new_lst
[3, 4, 5, 1, 6, 2, 7]

参考并感谢

猜你喜欢

转载自blog.csdn.net/wang725/article/details/81271858