简体   繁体   English

我想要多个列表指向 python 中的相同 memory

[英]I want multiple lists pointing to the same memory in python

I know this doesn't work, but it illustrates my goal.我知道这行不通,但它说明了我的目标。 If I have a list C, and I set A=C, then they point to the same object, which is what I want.如果我有一个列表 C,并且我设置 A=C,那么它们指向同一个 object,这就是我想要的。 But if I set A to a subset of C, then it creates a new list.但是如果我将 A 设置为 C 的子集,那么它会创建一个新列表。 I don't want that.我不想那样。 I want it to point to the same data.我希望它指向相同的数据。 Eg:例如:

C = [1,2,3,4,5,6]
A = C[3:6]
C[4] = 9
print(C)
print(A)

I would like to see [4,9,6] for A我想看到 [4,9,6] 的 A

Python lists don't do that. Python 列表不这样做。 It's something numpy arrays do:这是numpy arrays做的事情:

In [123]: import numpy as np

In [124]: c = np.array([1,2,3,4,5,6])

In [125]: c
Out[125]: array([1, 2, 3, 4, 5, 6])

In [126]: a = c[3:6]

In [127]: a
Out[127]: array([4, 5, 6])

In [128]: c[4] = 9

In [129]: c
Out[129]: array([1, 2, 3, 4, 9, 6])

In [130]: a
Out[130]: array([4, 9, 6])

You could do that with Python lists if each element was also a list or any mutable object:如果每个元素也是一个列表或任何可变的 object,您可以使用 Python 列表来做到这一点:

>>> c = [[1], [2], [3], [4], [5], [6]]  # list of lists
>>> a = c[3:6]
>>> a
[[4], [5], [6]]
>>> c[4].append(9)
>>> c
[[1], [2], [3], [4], [5, 9], [6]]
>>> a  # has also changed
[[4], [5, 9], [6]]
>>> c[4].pop(0)  # remove the first element of c[4]
5
>>> a
[[4], [9], [6]]
>>>

But you can't "overwrite" the value of c[4], only change it.但是您不能“覆盖” c[4] 的值,只能更改它。 Hence, works only with mutable objects that are themselves being changed.因此,仅适用于本身正在更改的可变对象。

>>> c[4] = 0
>>> c
[[1], [2], [3], [4], 0, [6]]
>>> a  # does not have the 0, retains previous value
[[4], [9], [6]]
>>>

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

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