为什么 python 中的列表会这样?

Why do lists in python behave this way?

如果我有如下函数和代码:

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']

因为在 do_something 中,您正在修改具有标签 a 的列表,但您正在创建一个新列表并将其重新分配给标签 b,而不是修改带有标签 b

这意味着 do_something 之外的 a 列表已更改,但 b 列表未更改,因为您只是巧合地在 func 中使用了相同的名称,您也可以用不同名称的 func 做同样的事情,例如:

def do_something(x, y):
    x.insert(0, ’z’)
    y = [’z’] + y

并且您在外部的印刷品仍会像您报告的那样运行,因为函数内部和外部对象的标签不相关,在您的示例中它们恰好是相同的。

来自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和程序的"end"处打印的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 的更多信息。