python - 是否可以获得列表成员的指针?

标签 python pointers python-3.4

我看到了一些相关问题,我认为我的问题仍然没有得到解答。如何获得列表成员的指针(引用)?说,我有:

>>> 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/

相关文章:

python - Python 3.x 中的向量和矩阵

tkinter 显示信息 python 3

python - 我无法理解奇怪的行为

python - 程序与 map() 一起工作,但通过 pool.map() 引发 TypeError

python - 在 TOR 中选择特定的导出节点(使用 Python 代码)

python - 列出pandas数据框

c - 这个旧的 C 指针数学/宏的东西在做什么?

c - 手动指定字符串在内存中的地址

转换后比较指针值,还是一样相等?

python - 对列表关键参数进行排序