Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当两个列表与+连接时,会创建多少个列表副本;操作人员_Python_List_Concatenation_Add - Fatal编程技术网

Python 当两个列表与+连接时,会创建多少个列表副本;操作人员

Python 当两个列表与+连接时,会创建多少个列表副本;操作人员,python,list,concatenation,add,Python,List,Concatenation,Add,我已经阅读了很多信息,但我仍然不明白python是否真的复制了6个列表,例如它连接了[1,2,3,4]+[5,6]这两个列表python并没有复制列表的6个副本,而是将两个列表连接或连接成一个,即[1,2,3,4,5,6] Python中的列表连接:。否,仅复制引用。对象本身根本不会被复制。见此: class Ref: ''' dummy class to show references ''' def __init__(self, ref): self.ref = r

我已经阅读了很多信息,但我仍然不明白python是否真的复制了6个列表,例如它连接了
[1,2,3,4]+[5,6]
这两个列表python并没有复制列表的6个副本,而是将两个列表连接或连接成一个,即
[1,2,3,4,5,6]


Python中的列表连接:。

否,仅复制引用。对象本身根本不会被复制。见此:

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)]

假设有n个列表l1、l2、l3。。。 如果你加上它们,在某个地址上只有一个副本

例如:

id()返回对象的标识。

python为什么要复制这些列表的6个副本?列表的“副本”就是整个列表。如果列表包含6个项目,为什么要制作整个列表的6个副本?您是指该列表中的6个元素吗?不,Python如何使用+运算符将两个列表串联起来。当我们谈论itertools.chain时,它使用生成器,但具体的机制是什么?我已经读过了,但我也找到了这篇文章
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