这段代码中list [:]的含义是什么? [英] What is the meaning of list[:] in this code?
问题描述
此代码来自Python的文档.我有点困惑.
This code is from Python's Documentation. I'm a little confused.
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)
为什么这段代码会创建一个无限循环,而第一个却没有呢?
Why does this code create a infinite loop and the first one doesn't?
推荐答案
这是陷阱之一! python,可以逃脱初学者.
This is one of the gotchas! of python, that can escape beginners.
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
,因此您要遍历未修改的副本.
The main thing to note here is that words[:]
returns a copy
of the existing list, so you are iterating over a copy, which is not modified.
您可以使用id()
检查是否引用了相同的列表:
You can check whether you are referring to the same lists using 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]
被称为 slicing operator ,它的作用是从索引i
直到(但不包括)返回列表的新副本.索引j
.
It is worth noting that [i:j]
is called the slicing operator, and what it does is it returns a fresh copy of the list starting from index i
, upto (but not including) index j
.
所以words[0:2]
给你
>>> words[0:2]
['hello', 'cat']
省略起始索引意味着它默认为0
,而省略最后一个索引意味着它默认为len(words)
,最终结果是您收到了 entire 列表的副本.
Omitting the starting index means it defaults to 0
, while omitting the last index means it defaults to len(words)
, and the end result is that you receive a copy of the entire list.
如果您想使代码更具可读性,建议使用copy
模块.
If you want to make your code a little more readable, I recommend the copy
module.
from copy import copy
words = ['cat', 'window', 'defenestrate']
for w in copy(words):
if len(w) > 6:
words.insert(0, w)
print(words)
这基本上与您的第一个代码段相同,并且更具可读性.
This basically does the same thing as your first code snippet, and is much more readable.
或者(如DSM在评论中所提到的)和在python> = 3上,您也可以使用words.copy()
来执行相同的操作.
Alternatively (as mentioned by DSM in the comments) and on python >=3, you may also use words.copy()
which does the same thing.
这篇关于这段代码中list [:]的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!