This question already has answers here:
How to remove items from a list while iterating?
                                
                                    (26个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试编写代码以删除列表中的重复项。这是第一个:

a = [2,2,1,1,1,2,3,6,6]
b = [2,2,1,1,1,2,3,6,6]
for x in a:
  a.remove(x)
  if x in a:
     b.remove(x)
print('the list without duplicates is: ', b)


不幸的是,它产生以下结果:

the list without duplicates is: [2, 1, 2, 3, 6]


然后,我尝试编写第二个:

a = [2,2,1,1,1,2,3,6,6]
b = [2,2,1,1,1,2,3,6,6]
for i in range(len(a)):
  for x in a:
    a.remove(x)
    if x in a:
        b.remove(x)
print('the list without duplicates is: ', b)


这第二个产生了我期望的结果:

the list without duplicates is:  [1, 2, 3, 6]


我真的不明白为什么第二个不同于第一个。实际上,如果我申请该清单:

[2,2,1,1,2,3,6,6]


他们两个产生相同的结果:

the list without duplicates is:  [1, 2, 3, 6]

最佳答案

why the second one is different

for循环跟踪它所在的索引。当您从列表中删除一个项目时,它会使计数混乱:位于索引i+1的项目现在已成为位于索引i的项目,并在下一次迭代中被跳过。

为了显示:

a_list = ['a','b','c','d','e','f','g','h']
for i, item in enumerate(a_list):
    print(f"i:{i}, item:{item}, a_list[i+1]:{a_list[i+1]}")
    print(f"\tremoving {item}", end = ' ---> ')
    a_list.remove(item)
    print(f"a_list[i+1]:{a_list[i+1]}")
>>>
i:0, item:a, a_list[i+1]:b
    removing a ---> a_list[i+1]:c
i:1, item:c, a_list[i+1]:d
    removing c ---> a_list[i+1]:e
i:2, item:e, a_list[i+1]:f
    removing e ---> a_list[i+1]:g
i:3, item:g, a_list[i+1]:h
....




第二种解决方案之所以有效,是因为即使您跳过了for循环中的项目,您仍然添加了一个外部循环,该循环可以重新访问该过程并对这些被跳过的项目进行操作。在上一次迭代中,因为您要跳过项目,所以总是剩下重复值之一。

关于python - 删除列表中的重复项。为什么我的代码出错? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48232726/

10-15 22:55
查看更多