Python列表添加和等同变量

时间:2017-12-14 20:47:56

标签: python list variables

我有以下代码

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 = [:]
do_something(a,b)

执行此操作后,所有变量均指的是:

a = ['z','a','b','c']
a1 = ['z','a','b','c']
a2 = ['a','b','c']
b = ['a','b','c']
b1 = ['a','b','c']
b2 = ['a','b','c']

我的问题是:
为什么a1改为包括' z'但是a2没有? 为什么b,b1和b2根本没有改变,即使b = [' z'] + b被执行了?
谢谢

2 个答案:

答案 0 :(得分:0)

这解释了a2问题:

def do_something(a,b):
    a.insert(0, 'z')
    print(id(b))
    b = ['z'] + b
    print(id(b))

a = ['a', 'b', 'c']; a1 = a; a2 = a[:]
b = ['a', 'b', 'c']; b1 = b; b2 = b[:]

do_something(a,b)

for var in (a,a1,a2,b,b1,b2):
    print(id(var), end=" ")
    print(var)

打印

4639127112                      # this is the id of b before new assign
4639513416                      # this is the id of b inside the function after
4639486216 ['z', 'a', 'b', 'c'] # a    (same as a1)
4639486216 ['z', 'a', 'b', 'c'] # a1
4639511944 ['a', 'b', 'c']      # a2
4639127112 ['a', 'b', 'c']      # b    (same as b1)
4639127112 ['a', 'b', 'c']      # b1
4639487304 ['a', 'b', 'c']      # b2

答案 1 :(得分:0)

我认为最简单的解释方法就是注释代码:

def do_something(a,b):
    a.insert(0, 'z')      #insert a 'z' at the start of a that has been passed into the function (modify it)
    b = ['z'] + b         #assign a local variable (b) to a list containing [z] concatenated with b

a = ['a', 'b', 'c']  #define normal list
a1 = a               #set a1 to refer to a (from now on they will always have the same contents
a2 = a[:]            #make a copy of a so this can have different contents to a
b = ['a', 'b', 'c']  #define normal list
b1 = b               #set b1 to refer to b
b2 = [:]             #make a copy of b

因此,b*变量都不会像调用函数时那样变化,它会修改 local 变量b

对于a变量,该函数会修改a,并且a1指向a,因此它也会修改a1。对于a2,这是在函数调用之前创建的原始a列表的副本,因此保留相同的['a', 'b', 'c']内容。