python - 删除列表中的重复项。为什么我的代码出错?

标签 python for-loop

我正在尝试编写代码来删除列表中的重复项。这是第一个:

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]

最佳答案

为什么第二个不同

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/

相关文章:

python - 使用嵌套 for 循环更新 dict

python - 是否有标准方法告诉 py.test 针对特定代码运行?

python - 如何在django中更改上传文件的名称和存储位置

c++ - 我做错了什么导致无限循环

python - 确定条件是否适用于列表的所有成员

Javascript - 使用 Promise 运行 for 循环

python - 无法在 python 中导入自定义 DLL

python - 问答: Defining __getitem__ method or assigning __getitem__ in classes

python - PySpark 应用程序失败,出现 java.lang.OutOfMemoryError : Java heap space

swift - 创建一个循环,每次调用一个值时加 40