简体   繁体   English

Python中多个空列表的初始化

[英]Initialization of multiple empty lists in Python

What is the correct way to initialize a bunch of variables to independent empty lists in Python 3?在 Python 3 中将一堆变量初始化为独立的空列表的正确方法是什么?

>>> (a, b) = ([],)*2
>>> a.append([2,3])
>>> a
[[2, 3]]
>>> b
[[2, 3]]
>>> b.append([2,3,])
>>> b
[[2, 3], [2, 3]]
>>> a
[[2, 3], [2, 3]]


>>> (a, b) = ([]  for _ in range(2))
>>> a.append([2,3])
>>> a
[[2, 3]]
>>> b
[]
>>> b.append([2])
>>> b
[[2]]
>>> a
[[2, 3]]

Why the first attempt does not allocate a , b independently in memory?为什么第一次尝试不在内存中独立分配ab

Why the first attempt does not allocate a, b independently in memory?为什么第一次尝试没有在内存中独立分配a、b? because they refer to same address in memory.因为它们引用内存中的相同地址。

(a, b) = ([],)*2
print(id(a))
print(id(b))
# 4346159296
# 4346159296
(a, b) = ([]  for _ in range(2))
print(id(a))
print(id(b))
# 4341571776
# 4341914304

You can initialize them as the following.您可以将它们初始化如下。

a = b = []
a = [2]
b = [2, 3]
print(a, b)

Why the first attempt does not allocate a, b independently in memory?为什么第一次尝试没有在内存中独立分配a、b?

Because you are using same list to define several variables.因为您使用相同的列表来定义多个变量。 It is something like:它是这样的:

list1 = []
var1, var2 = list1, list1

In your second case you are using comprehension which is creating new lists every iteration.在第二种情况下,您使用的是每次迭代都会创建新列表的理解。

You can have a look at this example你可以看看这个例子

list1 = [1, 2, 3]
a = [val for val in list1]
b = [val for val in list1]
c, d = ([list1]) * 2
print(f"{a=}")
print(f"{b=}")
print(f"{c=}")
print(f"{d=}")
print("Append something")
a.append("a append")
list1.append("list1 append")
print(f"{a=}")
print(f"{b=}")
print(f"{c=}")
print(f"{d=}")

Output:输出:

a=[1, 2, 3]
b=[1, 2, 3]
c=[1, 2, 3]
d=[1, 2, 3]
Append something
a=[1, 2, 3, 'a append']
b=[1, 2, 3]
c=[1, 2, 3, 'list1 append']
d=[1, 2, 3, 'list1 append']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM