为什么python中的列表以这种方式运行?

时间:2015-12-13 00:46:01

标签: python list immutability

如果我有以下功能和代码:

def do_something(a, b):
    a.insert(0, ’z’)
    b = [’z’] + b
a = [’a’, ’b’, ’c’]
a1 = a
a2 = a[:]
b = [’a’, ’b’, ’c’]
b1 = b
b2 = b[:]
do_something(a, b)

为什么print(a)会产生['z','a','b','c'],但打印b仍然只打印['a','b','c']

在我创建的b = b + ['z']函数中,所以z也不应该在列表中?

为什么打印a[:]不打印新列表['z','a','b','c']并打印旧列表['a','b','c']呢?

2 个答案:

答案 0 :(得分:5)

因为在do_something中您正在修改标签为a的列表,但您正在创建新列表并将其重新分配给标签b,而不是使用标签{修改列表} {1}}

这意味着b do_something之外的列表已被更改,但a之后的列表已更改,因为您只是巧合地在func中使用相同的名称,您也可以使用具有不同名称的func执行相同的操作,例如:

b

并且您在外面的打印件仍然会像您报告的那样表现,因为函数内部和外部的对象的标签不相关,在您的示例中它们恰好相同。

答案 1 :(得分:0)

来自https://docs.python.org/2/library/copy.html

Shallow copies of dictionaries can be made using dict.copy(), and of lists by 
assigning a slice of the entire list, for example, copied_list = original_list[:].

def do_something(a, b):
    a.insert(0, 'z') #this is still referencing a when executed. a changes.
    b = ['z'] + b #This is a shallow copy in which the b in this function, is now [’a’, ’b’, ’c’, 'z']. 

虽然上面的描述是正确的,但是你想到的是'z'与将在程序的“结尾”打印的b不同。打印在第一行的b是函数def_something()中的 b

代码:

def do_something(a, b):
    a.insert(0, 'z') #any changes made to this a changes the a that was passed in the function.
    b = ['z'] + b #This b is do_something() local only. LEGB scope: E. Link below about LEGB. 
print("a b in function: ", a, "|", b)
a = ['a', 'b', 'c']
a1 = a
a2 = a[:] #This is never touched following the rest of your code.
b = ['a', 'b', 'c']
b1 = b
b2 = b[:] #This is never touched following the rest of your code.
print("a b before function: ", a, "|", b)
do_something(a, b)
print("a b after function: ", a, "|", b) #This b is same thing it was after assignment.  

输出:

a b before function:  ['a', 'b', 'c'] | ['a', 'b', 'c']
a b in function:  ['z', 'a', 'b', 'c'] | ['z', 'a', 'b', 'c']
a b after function:  ['z', 'a', 'b', 'c'] | ['a', 'b', 'c']

有关LEGB的更多信息。