Joh*_*nny 1 python loops list infinite-loop
我刚刚浏览了python docs教程的循环技术章节,我在这里有一个关于这个男孩的问题: [:]
我了解到它需要字符串的开始和结束索引,因此:
text = "This is text"
text[:] # will return the whole text "This is text" and
tex[:4] # will return "This".
Run Code Online (Sandbox Code Playgroud)
但是当我在这里看到这段代码时......
words = ['cat', 'dog', 'cowcowcow']
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
print words
Run Code Online (Sandbox Code Playgroud)
输出:
['cowcowcow', 'cat', 'dog', 'cowcowcow']
Run Code Online (Sandbox Code Playgroud)
...我不理解for循环中[:]的含义.我会写的
for w in words:
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,这是一个无休止的循环,为什么呢?
[:]
表示从列表的开头到开头的范围 - 它实质上是复制列表(我通常主张使用list(...)
而不是为了可读性,它做同样的工作,并且适用于所有的迭代,而不仅仅是序列).
这里的问题是你在循环时修改列表,这意味着有更多的条目要循环,所以它变得无限.
通常,在迭代时修改列表是一个坏主意.相反,请考虑列表推导来构建新列表.
此代码以相反的顺序放置列表开头长度超过6的所有单词.所以另一种实现方式是:
words = [w for w in reversed(words) if len(w) > 6] + words
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
362 次 |
最近记录: |