python - list[ :] in this code? 是什么意思

标签 python list for-loop iteration

此代码来自 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/

相关文章:

java - 将 ListView 添加到 pageindicator fragment

python - 从第二个列表中减去第一个列表中的元素

r从数据框中提取列表元素

python - 如何 for 循环遍历两个嵌套循环内的字符串列表并避免外部循环造成的冗余?

python - TF Hub微调错误: ValueError: Failed to find data adapter that can handle input

python - Pandas DataFrames 列未被识别为数字

c - 如何使我的程序在每个给定时间(例如 1/s)仅迭代一次?

java - 如何解决这段代码中的 ArrayIndexOutOfBoundsException?

python - 如何从wav取得中间时间范围。 python

python - 远程 python 和 django 控制台在更新到 3.1 后不起作用