2012-04-14 99 views

回答

25
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的主要事情是:

  1. a_list必须已经指向
  2. 该对象被修改,而不是在一个新的对象指向a_list,对象
  3. 该对象必须支持__setitem__slice指数
  4. 右边的对象必须支持迭代
  5. 没有名称指向右侧的对象。如果没有其他引用(例如,当它是一个字面值时),那么在迭代完成后它将被引用计数不存在。
+0

我特别喜欢编辑的部分:) – 0xc0de 2012-04-14 18:28:37

+0

我在文档(http://docs.python.org/tutorial/introduction.html#lists)中阅读了这个内容。只是默认的索引是我的怀疑:) – 0xc0de 2012-04-14 19:00:27

+1

“对于列表,如果切片指定的范围与可迭代的长度不同,则列表将调整大小。”只有当范围的步长值为1时才是如此。对于除1以外的步长值,分配的迭代必须产生正确数量的项目。 – 2012-04-15 16:57:31

12

区别相当大!在

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 
2

通过分配到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保持其原始价值。

相关问题