为什么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']所以不应该在列表中以及?

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

If I have the following function and code:

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)

Why does print(a) yield ['z','a','b','c'], but printing b still only prints ['a','b','c']?

In the function I made b = b + ['z'] so shouldn't z be in the list as well?

Also why does printing a[:] not print the new list ['z','a','b','c'] and prints the old list ['a','b','c'] instead?

最满意答案

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

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

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

并且外部的打印件仍然会按照您的报告进行操作,因为函数内部和外部的对象标签无关,在您的示例中它们恰好相同。

Because in do_something you are modifying the list that has the label a but you are creating a new list and reassigning that to label b, not modifying the list with the label b

That means the list outside do_something for a has been changed, but not the b one, because you're just coincidentally using the same names inside the func, you could also do the same thing with the func with different names like:

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

and your prints on the outside would still behave as you report, because the labels for the objects inside the function and outside are not related, in your example they just happen to be the same.

更多推荐