For循环迭代的次数少于我在Python中预期的次数 [英] For loop iterates less times than I expected in Python

查看:191
本文介绍了For循环迭代的次数少于我在Python中预期的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的循环迭代六次,而不是用python3迭代三遍.我不了解这种行为. 我知道列表在删除元素时会发生变化,但是我不知道这会如何影响for循环条件. 为什么循环迭代少于六次?

I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior. I understand that the list changes as I delete elements but I don't get how that affects the for loop condition. Why is the loop iterating less than six times?

a = [1, 2, 3, 4, 5, 6]
for elem in a:
        del a[0]
        print(a)

推荐答案

您将通过del a[0]删除循环的每个迭代中的第一个元素,因此,迭代器将分3步清空,因为迭代器将在之后移动到该元素您在下一次迭代中删除的代码. 您可以检查迭代器当前所在的元素,并在下面的代码中查看列表状态

You are deleting the first element in every iteration of the loop by del a[0], so the iterator is emptied in 3 steps, because it moves to the element after the one you removed on the next iteration. You can check the element the iterator is currently on, and the list status in the code below

a = [1, 2, 3, 4, 5, 6]
for elem in a:
    print(elem)
    del a[0]
    print(a)

输出为

1
[2, 3, 4, 5, 6]
3
[3, 4, 5, 6]
5
[4, 5, 6]

您可以将其视为指向列表中第一个元素的指针,当您在每次迭代中删除第一个元素时,该指针跳2个步骤,而6个元素只能跳3次.

You can think of it as a pointer pointing to the first element of the list, that pointer jumps 2 steps when you delete the first element on each iteration, and it can jump only 3 times for 6 elements.

通常,修改要迭代的相同列表是一个坏主意. 但是,如果您确实要删除列表,则可以遍历列表a[:]的副本

Generally it is a bad idea to modify the same list you are iterating on. But if you really want to, you can iterate over the copy of the list a[:] if you really want to delete items

a = [1, 2, 3, 4, 5, 6]
for elem in a[:]:
    del a[0]
    print(a)

输出为

[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]

这篇关于For循环迭代的次数少于我在Python中预期的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆