【问题标题】:Iterating over the elements of a list and perform 'list.remove(x)', but the list is not empty after the iteration [duplicate]迭代列表的元素并执行'list.remove(x)',但迭代后列表不为空[重复]
【发布时间】:2019-02-14 11:51:45
【问题描述】:
a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
b = a
for i in b:
    a.remove(i)
print(a)

输出是 [3, 5, 12, 17, 4321, 13579] 而不是预期的空列表,为什么会这样?

实际上我想编写一个程序来删除列表中至少有一个偶数位的所有整数,即

a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
b = a
for i in b:
    if str(j) == 0 or str(j) == 2 or str(j) == 4 or str(j) == 6 or str(j) == 8:
        a.remove(i)
print(a)

但这并没有按预期的方式工作。我应该如何调试它?

【问题讨论】:

    标签: python


    【解决方案1】:

    问题在于,每次删除元素时,都会使列表变短,但要保持循环中的位置不变。本质上,在这样的循环中删除时,您会跳过所有其他元素。考虑示例a = [1,2,3]。在第一次迭代中,您删除了1。所以a 变成了[2,3] 并且你将你的位置移动到第二个元素,现在是3,所以你已经跳过了2

    如何解决它是通过使用列表理解进行过滤。这是一个例子:

    a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
    filtered = [x for x in a if not any(digit in str(x) for digit in '02468')]
    

    【讨论】:

      【解决方案2】:

      在迭代集合时修改集合(尤其是修改长度的操作)是禁忌。移除元素时,您正在从脚下拉出地毯。

      如果你倒着做,它会起作用:

         for i in reversed(b):
             a.remove(i)
         print(a)
      

      【讨论】:

        【解决方案3】:

        迭代槽列表而不是删除元素不是一件好事:

        所以

        a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
        b = a
        for i in b:
            a.remove(i)
        print(a)
        

        顺便说一句,ba 相同,现在因为你应该这样做:

        b=a[:]
        

        或:

        b=a.copy()
        

        要解决它,请执行以下操作:

        a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
        b = a[:]
        for i in b[:]:
            a.remove(i)
        print(a)
        

        或者:

        a = [2, 3, 4, 5, 10, 12, 13, 17, 1234, 4321, 12345, 13579]
        b = a[:]
        while len(a):
            a.pop()
        print(a)
        

        见:How to clone or copy a list?

        还有:How to remove list elements in a for loop in Python?

        也回答做:

        print([i for i in a any(i.__contains__(x) for x in range(0,10,2))])
        

        【讨论】:

          猜你喜欢
          • 2023-03-23
          • 1970-01-01
          • 2013-01-23
          • 1970-01-01
          • 2016-09-21
          • 1970-01-01
          • 2018-04-26
          • 2016-12-11
          • 2015-12-25
          相关资源
          最近更新 更多