python-3.x - 删除列表中特定重复编号的所有条目的函数

标签 python-3.x

如何从列表中删除特定编号的所有条目。

但是我下面的方法只是删除一次

newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
    if newList.count(num) > 1:
        newList.remove(num)
print(newList)

结果

[1, 3, 4, 2, 6, 7, 5, 8]

最佳答案

您的代码有 2 个问题:

  • 您在迭代列表的同时修改它。所以你错过了下一个数字(“3”和第二个“2”)
  • help(list.remove) 明确表示它将“删除第一次出现的值”

在你的代码中有几个打印,这变得很明显:

newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
    print (num)
    if newList.count(num) > 1:
        print('   -->removing')
        newList.remove(num)
print(newList)

输出:

1
2
   -->removing
4
5
   -->removing
6
7
5
8

关于python-3.x - 删除列表中特定重复编号的所有条目的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154659/

相关文章:

python - Python 中的石头剪刀布

python - 从多个类继承相同的函数名

python - 使用 pyinstaller 在 pygame 脚本中包含声音文件

python - 在同一台机器上同时运行 python 2.6 和 3.1

python - Python 中的时间(以毫秒为单位)

python - 在导入 pandas 之前跳过每个指定行

python - Twilio 环境变量错误

python - 在 Python 3 中有效地初始化大小为 n*m 的二维数组?

python - 如何创建包含 27.000 条线的抖动图?

python - sqlalchemy postgres : AttributeError: can't set attribute