python – 这段代码中list [:]的含义是什么?
发布时间:2020-12-20 10:32:19 所属栏目:Python 来源:网络整理
导读:参见英文答案 What is the difference between list and list[:] in python?????????????????????????????????????6个 此代码来自Python的文档.我有点困惑. words = ['cat','window','defenestrate']for w in words[:]: if len(w) 6: words.insert(0,w)print
参见英文答案 >
What is the difference between list and list[:] in python?????????????????????????????????????6个
此代码来自Python的文档.我有点困惑. words = ['cat','window','defenestrate'] for w in words[:]: if len(w) > 6: words.insert(0,w) print(words) 以下是我最初的想法: words = ['cat','defenestrate'] for w in words: if len(w) > 6: words.insert(0,w) print(words) 为什么这段代码创建了一个无限循环而第一个没有? 解决方法
这是陷阱之一! python,可以逃脱初学者.
[:]这个词在这里是神奇的酱汁. 注意: >>> words = ['cat','defenestrate'] >>> words2 = words[:] >>> words2.insert(0,'hello') >>> words2 ['hello','cat','defenestrate'] >>> words ['cat','defenestrate'] 现在没有[:]: >>> words = ['cat','defenestrate'] >>> words2 = words >>> words2.insert(0,'defenestrate'] >>> words ['hello','defenestrate'] 这里要注意的主要是单词[:]返回现有列表的副本,因此您将迭代一个未修改的副本. 您可以使用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. 所以,单词[0:2]给你 >>> words[0:2] ['hello','cat'] 省略起始索引意味着它默认为0,而省略最后一个索引意味着默认为len(单词),最终结果是您收到整个列表的副本. 如果您想让代码更具可读性,我推荐使用复制模块. from copy import copy words = ['cat','defenestrate'] for w in copy(words): if len(w) > 6: words.insert(0,w) print(words) 这基本上与您的第一个代码片段完全相同,并且更具可读性. 或者(如评论中的DSM所述)和python> = 3,您也可以使用words.copy()来执行相同的操作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |