如何在列表变量之间创建动态链接

2024-10-01 09:40:27 发布

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

字典的方法.viewvalues().viewkeys()允许创建在每次字典修改时链接和动态更新的列表变量,例如:

diction={'one':1,'two':2,'three':3}
dict_values=dictVar.viewvalues()
dict_keys=dictVar.viewkeys()

我想知道是否可以通过列表实现类似的功能。因此,如果有两个“源”列表变量,第三个列表是两个之和的结果:

a=[1,2,3]
b=[4,5,6]
sum=a+b

现在我想要的是一个列表变量sum在修改列表变量a或列表变量b时更新。如何做到这一点?你知道吗


Tags: 方法列表字典链接动态onedictthree
3条回答

您必须为自定义数据结构设置权限才能执行此操作。这是正确的方向。。。你知道吗

class LinkedArrays(object):
    def __init__(self, sourceArray1, sourceArray2, combineFunction):
        self.sa1, self.sa2 = sourceArray1, sourceArray2

        self.__combineFunction = combineFunction
        self.__update()

    def updateSourceArray1(self, index, value):
        self.sa1[index] = value
        self.__update()

    def updateSourceArray2(self, index, value):
        self.sa2[index] = value
        self.__update()

    def __update(self):
        self.combinedArray = [self.__combineFunction(self.sa1[i], self.sa2[i]) for i in range(len(self.sa1))]

    def __getitem__(self, item):
        return self.combinedArray[item]


summedArrays = LinkedArrays([1, 2, 3], [4, 5, 6], lambda x, y: x+y)
print summedArrays[0]  # print 5

summedArrays.updateSourceArray1(0, 6)
print summedArrays[0]  # print 10

我会定义一个函数来完成它,然后在需要列表时调用它。你知道吗

a=[1,2,3]
b=[4,5,6]

def sum(a, b):
    return a + b

然后,在口译员中:

>>> sum(a, b)
[1, 2, 3, 4, 5, 6]
>>> a.append(5)
>>> sum(a, b)
[1, 2, 3, 5, 4, 5, 6]

如果不需要一个简单的列表,你可以很容易地做你想做的事。你知道吗

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> sum = [a, b]
>>> print(sum)
[[1, 2, 3], [4, 5, 6]]
>>> a.append(8)
>>> print(sum)
[[1, 2, 3, 8], [4, 5, 6]]

也就是说,我建议不要定义名为sum的变量,因为它是built-in Python function。你知道吗

您可以用numpy数组来实现。你知道吗

>>> import numpy as np
>>> ab = np.array([1,2,3,4,5,6])
>>> a = ab[:3]
>>> b = ab[3:]
>>> a, b
(array([1, 2, 3]), array([4, 5, 6]))
>>> a[1] = 9
>>> ab
array([1, 9, 3, 4, 5, 6])
>>> ab[0] = 7
>>> a
array([7, 9, 3])

这里,ab是数组ab上的“视图”,修改一个视图也会修改另一个视图。你知道吗

ab开始,只需从a+b创建一个numpy数组,并相应地重新定义ab

>>> a, b = [1,2,3], [4,5,6]
>>> ab = np.array(a+b)
>>> a, b = ab[:3], ab[3:]

相关问题 更多 >