在python中更新集合中元组的值

时间:2018-02-15 20:42:49

标签: python python-3.x set

目前我有一些代码,它接受一组元组,每个元组都有格式(A,B)。在整个过程中,每个A都有一个与之相连的多个B.我想创建另一个包含格式(A,B1,B2,B3)的元组的集合,其中B1,B2,B3等是与第一组中的A相关联的B的值。目前我有这段代码:

data_set = set(tuple(x) for x in data) #converts given list of lists to set of tuples
association = set() #empty set to add (A, B1, B2, etc.) tuples
    for j in data_set: #loop through data set
        if (j[0]) not in association:
            associaton.add((j[0])) #This makes the first value of of my new tuple the value I want to find
        else:
           #I want to replace the current tuple with the current tuple plus the value of j[1]

如何找到与更新关联的正确元组。我计划使用A = A +(j [1])更新元组A.

2 个答案:

答案 0 :(得分:4)

我会偏离窗口并声称你正在描述XY problem

看起来tuple不是您要查找的数据结构。如果您有(A, B)格式的元组列表,并希望按照第一个项目对它们进行分组,则可以使用dictionary这样的代码:

association = {}  # empty dictionary
for j in data_set:
    if j[0] not in association:
        association[j[0]] = []  # initialize empty list
    association[j[0]].append(j[1])

如果您的输入数据为(A, B1), (A, B2), (A, B3),则结果为{A: [B1, B2, B3]}

使用元组解包可以清除上面的代码:

association = {}  # empty dictionary
for key, value in data_set:
    if key not in association:
        association[key] = []  # initialize empty list
    association[key].append(value)

答案 1 :(得分:0)

您无法更改元组内部的值,但您可以做的是将其作为列表并使其成为元组。像这样:

tupl = ("a", "b", "c")
tupl = list(tupl)   # will change it to a list: ["a", "b", "c"]
tupl.append("d")    # appends "d" to the list
tupl = tuple(tupl)  # changes it back to a tuple ("a", "b", "c", "d")