为什么python中的列表会有这种行为?

2024-04-20 03:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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']?你知道吗


Tags: 函数代码功能a2列表defa1do
2条回答

因为在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与在程序的“结尾”处打印的b是不同的。但是,打印在第一行的b是函数def\u 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的详细信息。你知道吗

相关问题 更多 >