分页: 1 / 1

[已解决,非解释器Bug]为何这段Python代码死循环?Python解释器的Bug?

发表于 : 2016-07-27 19:12
科学之子
为何这段Python代码死循环?Python解释器的Bug?
Python版本: 3.4.2

代码: 全选

words = ['cat', 'window', 'defenestrate']
for w in words:  # Loop over a slice copy of the entire list.
 if len(w) > 6:
  words.insert(0, w)
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient
https://docs.python.org/3.4/tutorial/co ... statements
我试着把slice去掉了,结果就死循环?

Re: 为何这段Python代码死循环?Python解释器的Bug?

发表于 : 2016-07-27 19:46
susbarbatus
我猜是这样的吧:

代码: 全选

for w in words: 
实际执行的流程大概是这样,先检查 words[0],words[1],words[2] ...
上例中如果使用 slice 建了个 copy 的话,检查到 words[3] 发现已经到结尾了就结束了。
但没建 copy 的情况下,在 words[2] 执行的时候 insert 插入了新项到 words 中,
那么原来的 'defenestrate' 从 words[2] 变成了 words[3],
检查 words[3] 的时候会继续插入把它变成 words[4],就死循环了。

Re: 为何这段Python代码死循环?Python解释器的Bug?

发表于 : 2016-07-27 20:03
vickycq

Re: 为何这段Python代码死循环?Python解释器的Bug?

发表于 : 2016-07-27 20:19
astolia
弄个调试输出就一目了然了

代码: 全选

words = ['cat', 'window', 'defenestrate']
for w in words:  # Loop over a slice copy of the entire list.
    print(len(words))
    print(w)
    if len(w) > 6:
        words.insert(0, w)