在python中动态更改迭代器是否安全? [英] Is it safe to change the iterator dynamically in python?

查看:122
本文介绍了在python中动态更改迭代器是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python,我需要在列表迭代时动态地在列表中添加成员:

With python, I need to add members in a list dynamically when the list is iterated over:

i = [1,2,3,4,5]

for a in i:
    if a == 1:
        i.append(100)
    print a

保证是否正常工作?

推荐答案

您正在更改序列,而不是迭代器。 循环的在你要循环的对象上调用 iter(),创建一个循环迭代器。对于列表对象,创建的列表迭代器保留对原始列表和内部索引的引用,并且每次循环请求下一项(在迭代器上调用 next()),返回当前索引处的项目并递增索引。

You are changing the sequence, not the iterator. The for loop calls iter() on the object you are looping over, creating a loop iterator. For a list object, the list iterator created keeps a reference to the original list and an internal index, and every time the for loop asks for the next item (calls next() on the iterator), the item at the current index is returned and the index is incremented.

这种情况下它是安全的,因为循环迭代器对象将很乐意继续通过额外的项目。只要你没有无限期地将项目添加到 i ,循环就会完成。

In this case it is safe, as the loop iterator object will happily continue over the extra items. As long as you don't add items to i indefinitely, the loop will complete.

如果你要 i 中移除项目,但是,循环迭代器不会看到这些更改,您会得到令人惊讶的结果:

If you were to remove items from i, however, the loop iterator would not see those changes and you would get 'surprising' results:

i = [1, 2, 3, 4, 5]
for a in i:
   if a == 1:
       del i[0]
   print a

打印:

1
3
4
5

因为循环迭代器在下一次迭代中产生 i [1] ,现在是 3 ,而不是 2

because the loop iterator yields i[1] on the next iteration, which is now 3, not 2.

如果你要在当前迭代索引之前插入项。

您可以自己创建迭代器,并手动进行实验以了解会发生什么:

You can create the iterator yourself, and experiment manually to see what happens:

>>> i = [1, 2, 3, 4, 5]
>>> i_iter = iter(i)  # index starts at 0
>>> next(i_iter)      # now the index is 1
1
>>> del i[0]
>>> i
[2, 3, 4, 5]          # item at index 1 is 3
>>> next(i_iter)      # returns 3, next index is 2
3
>>> i.insert(0, 1)
>>> i
[1, 2, 3, 4, 5]       # item at index 2 is 3
>>> next(i_iter)      # returns 3, next index is 3
3

这篇关于在python中动态更改迭代器是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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