Python对list去重

Python对list去重

  • 方法一
    新建新的列表,利用not in命令去重。这种方法看起来不够简便,但是保留了原列表中的顺序。代码如下:
list1 = [1,2,3,4,1,1,2,5,4,3]
list2 = []
for i in list1:
    if i not in list2:
        list2.append(i)
print(list2)

这样最终的输出就为:[1, 2, 3, 4, 5]

  • 方法二
    利用set的自动去重功能,这种方法就是将列表先转化为集合再进一步转化为列表,利用了集合的去重功能。这种方法简洁,但无法保留原列表的顺序,看如下示例:
list1 = [1,5,4,1,1,2,5,4,3]
list2 = list(set(list1))
print(list2)

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

list1 = [1,2,3,4,5,1,2,3]
list2 = list(set(list1))
list2.sort(key = list1.index)
print(list2)

猜你喜欢

转载自www.cnblogs.com/LJ-LJ/p/9751281.html