【问题标题】:List erasing unexpected behavior [duplicate]列出擦除意外行为[重复]
【发布时间】:2017-01-08 13:20:41
【问题描述】:

我正在尝试通过代码删除循环中的每个元素来清除 python 列表

x=list(range(10000))
for i in x:
    x.remove(i)

我认为在这段代码之后 x 必须是 [] ,而是只删除列表的每个第二个元素。 len(x)=5000 而不是 0

为什么会这样?我究竟做错了什么。 谢谢

【问题讨论】:

标签: python python-2.7


【解决方案1】:
original_list = list(range(1000))
remove_list_elements = []

for i in range(0, len(original_list), 2): 
    remove_list_elements.append(original_list[i])

[original_list.remove(i) for i in remove_list_elements] 
print(len(original_list))

【讨论】:

    【解决方案2】:

    如果您想实现一个列表对象,该对象在迭代时会自行擦除,这将相当容易:

    class ErasingList(list):
        "a list implemented as an iterator, iterating over it will .pop() items off"
        def __iter__(self):
            return self
        def __next__(self):
            try:
                return self.pop(0)
            #or self.pop() to take from the end of the list which is less intuitive but more efficient
            except IndexError:
                raise StopIteration
        next = __next__ #vs2 compatibility.
    
    x = ErasingList(range(100))
    
    for i in x:
        print(i)
    
    print(x)
    

    【讨论】:

      【解决方案3】:

      如果你想像你一样清除一个python列表,正确的方法是使用x.clear,关于该方法的文档here,现在,如果你想使用一些奇特的条件删除元素,只需使用filter,清空整个x列表的例子:

      x = list(range(10000))
      x = filter(lambda x: False, x)
      print x
      

      【讨论】:

        【解决方案4】:

        a.remove(i) 搞砸了索引是我的猜测。

        改为使用

        a.clear()
        

        这是清除列表的好方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-25
          • 1970-01-01
          • 1970-01-01
          • 2013-10-19
          • 1970-01-01
          • 2013-05-30
          相关资源
          最近更新 更多