我有一个 python 列表:
x = [1,1,1]
我将 y 设置为等于该列表,然后更改 y 和 x,因为我有两个指针指向内存中的同一位置。
y = x
y[1] = 7
print x
[1, 7, 1]
这一切都很好。无论如何我可以列一个 x+y 的列表,这样当我改变 x 时,我也改变 y 吗?这是一些不起作用的代码,但也许 阐明我的目标:
q = x + y
print q
[1, 7, 1, 1, 7, 1]
q[0] = 2
print q
[2, 7, 1, 1, 7, 1]
但我希望 q 变成:
[2, 7, 1, 2, 7, 1]
我希望这是明确的,我更希望它是可以实现的!
编辑:为了回答关于为什么这有用的询问,我打算将它用作环形缓冲区。假设我想获取位置 p 的内容并将它们移动到位置 p+1:而不是:
if p+1 == len(q):
q[0]= q[p]
else:
q[p+1] =q[p]
我可以这样做:
q[p+1] = q[p]
最佳答案
这就是诀窍,即使是删除和插入元素:
from collections import MutableSequence
from itertools import chain, islice
class ChainedListProxy(MutableSequence):
def __init__(self, *lists):
self._lists=lists
def _resolve_element(self, index):
""" returning list and subindex in that list """
for l in self._lists:
if index>=len(l):
index-=len(l)
else:
return l, index
raise IndexError('index out of range')
def __getitem__(self, index):
l, i=self._resolve_element(index)
return l[i]
def __delitem__(self, index):
l, i=self._resolve_element(index)
del l[i]
def __setitem__(self, index, value):
if isinstance(index, slice):
indicies=index.indices(len(self))
l, i=self._resolve_element(index)
l[i]=value
def insert(self, index, value):
l, i=self._resolve_element(index)
l.insert(i, value)
def __len__(self):
return sum( (len(l) for l in self._lists) )
用法:
>>> x=[1,2,3]
>>> q=ChainedListProxy(x,x)
>>> q[0]
1
>>> q[3]=5
>>> q[0]
5
>>> list(q)
[5, 2, 3, 5, 2, 3]
关于python - 创建一个python列表,一个指针指向两个地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49680201/