当2个列表与+运算符连接时,会创建多少个列表副本?

问题描述 投票:0回答:3

我已经阅读了很多信息herehere但我仍然不明白是python真的制作了6个副本的列表,例如它连接[1,2,3,4] + [5,6]这两个列表

python list concatenation add
3个回答
1
投票

Python没有列表的6个副本,而是连接或连接两个列表并使它们成为一个,即[1,2,3,4,5,6]

列出Python中的连接:How to concatenate two lists in Python?


0
投票

不,只复制引用。根本不复制对象本身。看到这个:

class Ref:
   ''' dummy class to show references '''
   def __init__(self, ref):
       self.ref = ref
   def __repr__(self):
      return f'Ref({self.ref!r})'

x = [Ref(i) for i in [1,2,3,4]]
y = [Ref(i) for i in [5,6]]

print(x)   # [Ref(1), Ref(2), Ref(3), Ref(4)]
print(y)   # [Ref(5), Ref(6)]

z = x + y
print(z)   # [Ref(1), Ref(2), Ref(3), Ref(4), Ref(5), Ref(6)]

# edit single reference in place
x[0].ref = 100
y[1].ref = 200

# concatenated list has changed
print(z)  # Ref(100), Ref(2), Ref(3), Ref(4), Ref(5), Ref(200)]

0
投票

假设列表中有多个列表l1,l2,l3,...和如果添加它们,它在某个地址上只有一个副本。

例如:

In [8]: l1 = [1,2,3]
In [9]: l2 = [4,5,6]

In [10]: id(l1 + l2)
Out[10]: 140311052048072

In [11]: id(l1)
Out[11]: 140311052046704

In [12]: id(l2)
Out[12]: 140311052047136

id()返回对象的标识。 https://docs.python.org/2/library/functions.html#id

© www.soinside.com 2019 - 2024. All rights reserved.