Python3 - for循环删除列表项

时间:2016-12-02 09:18:04

标签: python python-3.x for-loop pycharm

我有代码:

listA = [i for i in range(5)]

for x in listA :
    print(listA)
    print('prepare to remove %s'%x)
    listA.remove(x)
    listA = [i for i in range(x, 10)]
    print(listA)

我想for循环中的x将是: 0 1 2 3 4

但结果是 0 2 3 4

为什么?这太奇怪了......

我只是想知道1为什么会消失,为什么不打印0 2 4或01234?只是1

有人可以解释一下吗?

4 个答案:

答案 0 :(得分:1)

参考下面的代码

  • 在第一次迭代中,lst.remove(x)有效地删除了1个项目 如果id为xxxx,则lst现为[1,2,3,4]
  • 在第二次迭代时,由于0已被删除,因此在尝试获取下一项时,它将在索引1处得到2
  • 从第二次迭代开始,就像@Harlekuin一样 提一下,你正在对一个全新的创建执行删除操作 列表,不会影响id为xxxx的原始列表,下面的迭代将继续在lst上用id xxxx [1,2,3,4],所以它的3跟随4

lst = [0, 1, 2, 3, 4] # define raw list to make it clearer
# id(lst) = xxxx

# iterate over lst with id xxxx
for x in lst: 
    print('prepare to remove %s'%x)
    lst.remove(x) # 1st loop operate on list with id xxxx, 2nd loop onwards operate on list with id yyyy
    lst = [i for i in range(x, 10)] # lst being assign to another id, lets assume its yyyy now
    # id(lst) = yyyy

答案 1 :(得分:0)

这是因为你删除x(是一个整数),然后用范围(x,10)重新创建列表。第一次执行此操作时,它将从原始列表中删除1,但在打印之前会重新创建列表,因此只有第一个循环会丢失一个数字。换句话说,

list.remove(x)
一旦你:

就没用了

list = [i for i in range(x, 10)]

答案 2 :(得分:0)

在第一个循环中,您从0中移除listA[0, 1, 2, 3, 4]引用原始[1, 2, 3, 4]并且您有for[1, 2, 3, 4]使用对同一列表的引用,因此在下一个循环中,它使用1并跳过listA

但同时您将新列表分配给变量1,因此在下一个循环中,您可以从新列表中删除for - 但[1, 2, 3, 4]仍然使用对原始$headers = $this->input->request_headers(); 的引用,并且它不会不要跳过其他元素。

答案 3 :(得分:0)

问题是您在循环条件和内部使用相同的列表。

loop: 0
list before removing 0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list after removing 0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
loop: 1
list before removing 1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list after removing 1
[0, 2, 3, 4, 5, 6, 7, 8, 9]
loop: 2
list before removing 2
[1, 2, 3, 4, 5, 6, 7, 8, 9]
list after removing 2
[1, 3, 4, 5, 6, 7, 8, 9]
loop: 3
list before removing 3
[2, 3, 4, 5, 6, 7, 8, 9]
list after removing 3
[2, 4, 5, 6, 7, 8, 9]
loop: 4
list before removing 4
[3, 4, 5, 6, 7, 8, 9]
list after removing 4
[3, 5, 6, 7, 8, 9]

这会产生以下输出:

handle_result(attributes->SetUINT32(MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, TRUE));
相关问题