分配一个列表给另一个列表

2024-03-29 12:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

listOne = [1, 2, 3]
listTwo = listOne

print(listOne) #[1, 2, 3]

listTwo.append(4)

print(listOne) #[1, 2, 3, 4]
print(listtwo) #[1, 2, 3, 4]

这里我怀疑的是,我们将列表1分配给列表2。是listTwo指向listOne。所以,当我们将值附加到listTwo时,为什么它也会在listOne中反映呢?我是python新手。请帮帮我。在


Tags: 列表指向printappend新手将值帮帮我listtwo
1条回答
网友
1楼 · 发布于 2024-03-29 12:23:34

在Python中,所有的东西都是一个对象,这意味着所有的东西都有自己的内存。在

初始化listOne = [1, 2, 3]时,会给它一个内存地址。在

然后使用赋值运算符=listOne的内存位置分配给listTwo。在

如果我们以你为例:

listOne = [1, 2, 3]
listTwo = listOne

我们可以:

^{2}$

有人提到你可以使用切片运算符:,但这给了你一个浅拷贝。如果您不熟悉浅拷贝和深拷贝的区别,请阅读这些docs。基本上,浅拷贝是一个新的外部容器对象([ ]),内部元素是对相同内存位置的引用。深度复制也是一个新的外部容器,但它会获得内部对象的全新副本(即对象的相同副本,但位于新的内存位置)。在

我给你留一个非灵长类的浅拷贝的例子(例如,不像你的int):

>>> class Sample:
        def __init__(self, num):
            self.num = num
            self.id = id(self)

>>> s1 = Sample(1)
>>> s2 = Sample(2)

>>> listOne = [s1, s2]
>>> listOne[0].num
1
>>> listOne[0].id
88131696
>>> listOne[1].num
2
>>> listOne[1].id
92813904

# so far we know that listOne contains these unique objects

>>> listTwo = listOne
>>> listTwo[0].num
1
>>> listTwo[0].id
88131696
>>> listTwo[1].num
2
>>> listTwo[1].id
92813904

# well shoot, the two lists have the same objects!
# another way to do show that is to simply print the lists

>>> listOne
[<__main__.Sample object at 0x0540C870>, <__main__.Sample object at 0x05883A50>]
>>> listTwo
[<__main__.Sample object at 0x0540C870>, <__main__.Sample object at 0x05883A50>]

# those odd number sequences are hexadecimal and represent the memory location
# to prove the point further, you can use the built in hex() with id()

>>> hex(listOne[0].id) # id is 88131696 from above
'0x540c870'

相关问题 更多 >