为什么修改被迭代的序列不安全? [英] Why is it not safe to modify sequence being iterated on?

查看:58
本文介绍了为什么修改被迭代的序列不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改循环中被迭代的序列是不安全的(这只会发生在可变序列类型,例如列表).如果您需要修改您正在迭代的列表(例如,复制选定的项目),您必须迭代一个副本.切片符号使这特别方便:

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:

   >>> for x in a[:]: # make a slice copy of the entire list
   ...    if len(x) > 6: a.insert(0, x)
   ... 
   >>> a
   ['defenestrate', 'cat', 'window', 'defenestrate']

为什么只做 for x in a 不安全??

why is it not safe to just do for x in a ??

推荐答案

不要太技术性:

如果您在 Python 中迭代一个可变序列,并且在迭代过程中该序列发生了变化,则并不总是完全清楚会发生什么.如果您在迭代时在序列中插入一个元素,那么现在可以合理地将什么视为序列中的下一个"元素?如果删除下一个对象怎么办?

If you're iterating through a mutable sequence in Python and the sequence is changed while it's being iterated through, it is not always entirely clear what will happen. If you insert an element in the sequence while iterating through it, what would now reasonably be considered the "next" element in the sequence? What if you delete the next object?

因此,在更改可变序列时迭代它会导致未指定的行为.任何事情都可能发生,具体取决于列表的实施方式.:-)

For this reason, iterating through a mutable sequence while you're changing it leads to unspecified behaviour. Anything might happen, depending on exactly how the list is implemented. :-)

这篇关于为什么修改被迭代的序列不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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