【问题标题】:Removing element messes up the index [duplicate]删除元素会弄乱索引[重复]
【发布时间】:2013-12-26 06:36:19
【问题描述】:

我有一个关于列表的简单问题

假设我想从一个列表中删除所有的 'a's:

list = ['a', 'a', 'b', 'b', 'c', 'c']
for element in list:
    if element == 'a':
        list.remove('a')

print list

==> 结果:

['a', 'b', 'b', 'c', 'c', 'd', 'd']

我知道这是因为,在我删除第一个 'a' 后,列表索引得到了

当所有元素向左推 1 时递增。

在其他语言中,我想解决这个问题的一种方法是从列表末尾向后迭代..

但是,遍历 reversed(list) 会返回相同的错误。

有解决这个问题的pythonic方法吗??

谢谢

【问题讨论】:

  • 反向迭代没有帮助,因为您使用的是remove,它从前面遍历列表并删除它找到的第一个出现。不要使用remove,除非你真的没有更好的选择。
  • 请不要使用list 名称作为变量。

标签: python list


【解决方案1】:

您不应该在迭代列表时修改它。

更好的方法是使用list comprehension 排除项目:

list1 = ['a', 'a', 'b', 'b', 'c', 'c']
list2 = [x for x in list1 if x != 'a']

注意:不要在 Python 中使用 list 作为变量名 - 它会掩盖内置的 list 类型。

【讨论】:

    【解决方案2】:

    更 Pythonic 的方式之一:

    >>> filter(lambda x: x != 'a', ['a', 'a', 'b', 'b', 'c', 'c'])
    ['b', 'b', 'c', 'c']
    

    【讨论】:

    • 我很好奇。是什么让这个 pythonic ?我希望,你的方式更快,但是一个错过放置角色和调试这会让我喝酒。我对 python 很陌生,真的很好奇。
    • 我想是因为它使用了为此确切目的定义的方法:Return those items of sequence for which function(item) is true.
    【解决方案3】:

    您是对的,当您在迭代列表时从列表中删除项目时,列表索引会不同步。其他现有答案都暗示您需要创建一个新列表并仅复制您想要的项目。

    例如:

    existing_list = ['a', 'a', 'b', 'c', 'd', 'e']
    
    new_list = []
    
    for element in existing_list:
        if element != 'a':
            new_list.append(element)
    
    existing_list = new_list
    print existing_list
    

    输出:['b', 'c', 'd', 'e']

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 2013-12-02
      • 2011-02-18
      相关资源
      最近更新 更多