它提到了类似的内容:如果我们不复制列表,则它将为列表words = ['cat', 'window', 'defenestrate']
打印无限的列表值;但如果我们事先使用"for w in words[:]"
对其进行复制,则不会。我需要一个解释。
words = ['cat', 'window', 'defenestrate']
for w in words :
if len(w) > 6:
words.insert(0,w)
此代码将在无限循环中运行,但如果我们将for w in
wordswith
换成w [inwords ::],则不会运行
[:]
,您将在那时创建列表内容的副本,这将是:words = ['cat', 'window', 'defenestrate'] # equals words[:]
for i, w in enumerate(words[:]):
print(i, w)
if len(w) > 6:
words.insert(0,w)
print("len:", len(words))
#0 cat
#1 window
#2 defenestrate
#len: 4
但是使用words
变量本身,单步执行无济于事,因为在第一个位置的插入被取消了,前进的步已被取消:
words = ['cat', 'window', 'defenestrate'] for i, w in enumerate(words): print(i, w) if len(w) > 6: words.insert(0,w) print("len:", len(words)) #0 cat #1 window #2 defenestrate #len: 4 #3 defenestrate #len: 5 #4 defenestrate #len: 6 #5 defenestrate #len: 7 #6 defenestrate #len: 8 #7 defenestrate #len: 9 #...
首先,创建列表:words
words = ['cat', 'window', 'defenestrate']
基于单词创建两个新变量:
words_copy = words[:] # this is a copy words_ref = words # this is reference
值仍然相等:
assert words == words_copy assert words == words_ref
但是菜单中断不是:
assert id(words) != id(words_copy) assert id(words) == id(words_ref)
接下来,我们将修改列表(就像您在循环中一样):
words.append('foo')
现在,副本的值不相等,但是对于引用而言,值仍然相等:
assert words != words_copy assert words == words_ref assert id(words) != id(words_copy) assert id(words) == id(words_ref)
因此,通过获取数组的副本并在循环中使用它,您无需在循环内修改对象。简单!