我在很多地方都看到使用list
s的片分配。我能够用(非默认)指数使用时要了解其使用,但我无法理解它像使用:切片整个列表和直接分配的切片分配之间有什么区别?
a_list[:] = ['foo', 'bar']
是如何从
a_list = ['foo', 'bar']
不同?
我在很多地方都看到使用list
s的片分配。我能够用(非默认)指数使用时要了解其使用,但我无法理解它像使用:切片整个列表和直接分配的切片分配之间有什么区别?
a_list[:] = ['foo', 'bar']
是如何从
a_list = ['foo', 'bar']
不同?
a_list = ['foo', 'bar']
在内存中创建一个新的list
和它指向的名字a_list
。这与a_list
之前指出的无关。
a_list[:] = ['foo', 'bar']
调用a_list
对象与slice
作为索引,并在存储器中作为值创建了新的list
方法__setitem__
。
__setitem__
评估slice
以找出它所代表的索引,并在其传递的值上调用iter
。然后它遍历该对象,将slice
指定的范围内的每个索引设置为该对象的下一个值。对于list
s,如果由slice
指定的范围与可迭代的长度不同,则调整list
的大小。这允许你做一些有趣的东西,如一个列表删除部分:
a_list[:] = [] # deletes all the items in the list, equivalent to 'del a_list[:]'
或列表中的中间插入新的价值观:
a_list[1:1] = [1, 2, 3] # inserts the new values at index 1 in the list
然而,随着“扩展切片” ,其中step
不是一个,可迭代必须是正确的长度:
>>> lst = [1, 2, 3]
>>> lst[::2] = []
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: attempt to assign sequence of size 0 to extended slice of size 2
是约切片分配给不同a_list
的主要事情是:
a_list
必须已经指向a_list
,对象__setitem__
有slice
指数区别相当大!在
a_list[:] = ['foo', 'bar']
您修改了一个绑定到名称a_list
的现有列表。另一方面,
a_list = ['foo', 'bar']
给名称a_list
分配一个新列表。
也许这将帮助:
a = a_list = ['foo', 'bar'] # another name for the same list
a_list = ['x', 'y'] # reassigns the name a_list
print a # still the original list
a = a_list = ['foo', 'bar']
a_list[:] = ['x', 'y'] # changes the existing list bound to a
print a # a changed too since you changed the object
通过分配到a_list[:]
,a_list
仍然参考同一个列表对象,与修改的内容。通过分配a_list
,a_list
现在引用新的列表对象。
退房其id
:
>>> a_list = []
>>> id(a_list)
32092040
>>> a_list[:] = ['foo', 'bar']
>>> id(a_list)
32092040
>>> a_list = ['foo', 'bar']
>>> id(a_list)
35465096
正如你可以看到,它的id
与切片分配版本好好尝试一下改变。
两者之间的不同可能会导致完全不同的结果,例如,当列表的功能参数:
def foo(a_list):
a_list[:] = ['foo', 'bar']
a = ['original']
foo(a)
print(a)
有了这个,a
被修改为好,但如果a_list = ['foo', 'bar']
是相反,a
保持其原始价值。
我特别喜欢编辑的部分:) – 0xc0de 2012-04-14 18:28:37
我在文档(http://docs.python.org/tutorial/introduction.html#lists)中阅读了这个内容。只是默认的索引是我的怀疑:) – 0xc0de 2012-04-14 19:00:27
“对于列表,如果切片指定的范围与可迭代的长度不同,则列表将调整大小。”只有当范围的步长值为1时才是如此。对于除1以外的步长值,分配的迭代必须产生正确数量的项目。 – 2012-04-15 16:57:31