我看到了一些相关问题,我认为我的问题仍然没有得到解答。如何获得列表成员的指针(引用)?说,我有:
>>> a = [None]
>>> d = a[0]
>>> d = 3
我期望得到:
>>> a
[3] # But I get [None] of course.
Python 中可能吗?或者我该如何实现?
更新
我的最终目标是更改来源。
最佳答案
不,这是不可能的。您无法存储对列表中某个位置的引用并尝试稍后通过分配来更新它。
如果您想实现解决方法,那么您可能需要使用闭包来捕获对列表中所需索引的引用。这是一个例子:
# Here's my list
mylist = [1, 2, 3, 4]
# Save a reference to the list using a function to close over it
def myref(x): mylist[1] = x
# Update the referenced value to 7
myref(7)
# mylist is now [1, 7, 3, 4]
print mylist
你被困在使用 myref(7)
语法而不是 myref = 7
语法,因为在 Python 中没有办法重载赋值运算符,但我认为将为您工作。
在您对其他答案之一的评论中,您提到您实际上正在处理一个 n 维列表,并且您想要保存一个引用,以便稍后在索引不在范围内时可以更新它。这对于这种情况也很有效。这是一个例子:
# My 3D list
list3D = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
# Find
def findEntry(data, x):
for i, page in enumerate(data):
for j, row in enumerate(page):
for k, col in enumerate(row):
if col == x:
def myref(y): data[i][j][k] = y
return myref
# Get a reference to the first cell containing 4
updater = findEntry(list3D, 4)
# Update that cell to be 44 instead
updater(44)
# list3D is now [[[1, 2], [3, 44]], [[5, 6], [7, 8]]]
print list3D
关于python - 是否可以获得列表成员的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901337/