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

软件和网站开发以及相关技术探讨
回复
科学之子
帖子: 2284
注册时间: 2013-05-26 6:58
系统: Debian 9

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

#1

帖子 科学之子 » 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去掉了,结果就死循环?
上次由 科学之子 在 2016-07-28 10:21,总共编辑 1 次。
头像
susbarbatus
帖子: 2966
注册时间: 2010-04-10 16:14
系统: Arch Linux

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

#2

帖子 susbarbatus » 2016-07-27 19:46

我猜是这样的吧:

代码: 全选

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],就死循环了。
沉迷将棋中……
头像
astolia
论坛版主
帖子: 6396
注册时间: 2008-09-18 13:11

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

#4

帖子 astolia » 2016-07-27 20:19

弄个调试输出就一目了然了

代码: 全选

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)
回复