此代码来自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
现有列表的a,因此您要遍历未修改的副本。
您可以使用以下命令检查是否引用了相同的列表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]
它称为 切片运算符 ,它的作用是从index开始i
,直到(但不包括)index ,返回列表的新副本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()
后者执行相同的操作。
我正在学习Scala语言,我不明白这段代码: 当是时,是从的范围是什么意思?
我已经阅读了悬而未决的文件: http://developer.android.com/reference/android/app/PendingIntent.html 发送功能定义为: 公共无效发送(上下文上下文、int代码、Intent意图、OnFinated onFined、处理程序处理程序、字符串所需权限) 代码:“返回PendingEvent目标的结果代码。” 让我困惑的是参数。我应该什
在本例中,TLS版本是最高版本(1.2),还是我需要将TLS版本显式为 支持TLS 1.2版
代码来源 https://medium.com/geekculture/python-multiprocessing-with-ou... 这里的job.get()是表达什么呢?jobs是个list,每个job也不是queue,list的元素没有get方法,如何理解呢?
我想把这段代码添加到我的Java文件中: 但我不知道在哪。这是我的Java文件:包sherdle.donald.duck.app;导入android.app.activity;导入Android.os.bundle;导入Android.View.Window;导入android.webkit.webchromeclient;导入android.webkit.webview;导入Android.We
假设我们有以下三个类: 这将产生以下错误: 既然是整数,为什么它不选择类型?