此代码来自 Python 的文档。我有点困惑。
words = ['cat', 'window', 'defenestrate']
for w in words[:]:
if len(w) > 6:
words.insert(0, w)
print(words)
以下是我最初的想法:
words = ['cat', 'window', 'defenestrate']
for w in words:
if len(w) > 6:
words.insert(0, w)
print(words)
为什么这段代码创建了一个无限循环而第一个没有?
最佳答案
这是陷阱之一! python的,可以逃脱初学者。
words[:]
是这里的魔法酱。
观察:
>>> words = ['cat', 'window', 'defenestrate']
>>> words2 = words[:]
>>> words2.insert(0, 'hello')
>>> words2
['hello', 'cat', 'window', 'defenestrate']
>>> words
['cat', 'window', 'defenestrate']
现在没有 [:]
:
>>> words = ['cat', 'window', 'defenestrate']
>>> words2 = words
>>> words2.insert(0, 'hello')
>>> words2
['hello', 'cat', 'window', 'defenestrate']
>>> words
['hello', 'cat', 'window', 'defenestrate']
这里要注意的主要是 words[:]
返回 copy
现有列表的副本,因此您正在迭代未修改的副本。
您可以使用 id()
来检查您是否引用了相同的列表。 :
第一种情况:
>>> words2 = words[:]
>>> id(words2)
4360026736
>>> id(words)
4360188992
>>> words2 is words
False
第二种情况:
>>> id(words2)
4360188992
>>> id(words)
4360188992
>>> words2 is words
True
值得注意的是[i:j]
被称为切片操作符,它的作用是返回一个从索引i
开始的列表的新副本。 , 直到(但不包括)索引 j
.
所以,words[0:2]
给你
>>> words[0:2]
['hello', 'cat']
省略起始索引意味着它默认为 0
, 而省略最后一个索引意味着它默认为 len(words)
,最终结果是您会收到整个列表的副本。
如果你想让你的代码更具可读性,我推荐 copy
模块。
from copy import copy
words = ['cat', 'window', 'defenestrate']
for w in copy(words):
if len(w) > 6:
words.insert(0, w)
print(words)
这基本上和你的第一个代码片段做同样的事情,并且更具可读性。
或者(正如 DSM 在评论中提到的)和在 python >=3 上,您也可以使用 words.copy()
它做同样的事情。
关于python - list[ :] in this code? 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633798/