Python:remove() 似乎不起作用

标签 python

我搜索了一段时间,但找不到解决我的问题的方法。我对 Python 还是个新手,所以有时我会在一些显而易见的事情上遇到困难...提前感谢您的建议!

我有一个包含对象和这些对象的重复项的列表,两者都有特定的名称:objects_extduplicatedObject_SREF_ext。我想要的是,如果我的列表中有重复的对象,请检查原始对象是否也在列表中,如果是,则从列表中删除重复的对象。

我尝试使用 remove() 方法,因为列表中每个名称只能出现一次,但它不起作用。这是我的代码:

rawSelection = [u'crapacruk_high', u'doubidou_high', u'blahbli_high', u'crapacruk_SREF_high', u'doubidou_SREF_high', u'blahbli_SREF_high']
# objects with '_SREF_' in their names are the duplicated ones
for obj in rawSelection:
    if '_SREF_' in str(obj):
        rawName = str(obj).split('_')
        rootName = rawName [0]
        defName = rootName + '_' + '_'.join(rawName[2:])
        if defName in rawSelection:
            rawSelection.remove (obj)
# Always returns:
# [u'crapacruk_high', u'doubidou_high', u'blahbli_high', u'doubidou_SREF_high']
# Instead of:
# [u'crapacruk_high', u'doubidou_high', u'blahbli_high']

编辑:哦,忘了说,只有当原始对象也在列表中时,才必须从列表中删除重复的对象。

最佳答案

问题在于您正在改变正在迭代的同一个列表。

当您从列表中删除 u'crapacruk_SREF_high' 时,其后面的所有内容都会向左移动(这在 C 源代码级别上完成),因此 obj 的值现在是u'doubidou_SREF_high'。然后 for 循环结束,obj 成为列表中的下一个元素,u'blahbli_SREF_high'

要解决此问题,您可以复制列表并获取

for obj in rawSelection[:]:
  ...

关于Python:remove() 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749784/

相关文章:

python - "zypper install python-mysqldb mysql-server"找不到包

python - 重新排列列表中的项目,使得没有两个相邻项目是相同的

python - 在 numpy/pandas 中查找特定值之前的最后一个值

c++ - LLDB Python 脚本中的指针算法

Python 2.7 错误导入ROOT

python - 运行 Adam 优化器

Python Matplotlib slider 小部件未更新

python - 如何在Elasticsearch中从特定索引获取数据?

python - 如何在python pandas中键为空的地方进行右连接

python - 使用 zipfile 模块在 python 中创建带有压缩的 zip 文件