如何对元组对列表求和?

我有一个配对列表,每秒不断更新新值。如果每个元组中的第二个值等于每个元组中的第一个值,我需要对它们进行求和。我尝试过使用字典,但由于键是唯一的,它会覆盖以前的更新。


[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74)]

[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97)]

[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97), (3.05, 16.32)]

[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97), (3.05, 16.32), (3.05, 210.72)]

期望的输出:


[(3.05, 383.06), (3.1, 1157.59)]

我不得不重现这个问题,在原来的帖子中,数字每秒从 Excel 流入。当我使用字典时,新的更新键将替换旧的键,并根据唯一键记录新值。因此,很难将所有值与它们的键相加。这只是一个示例,更新将是 excel 提供的任何内容。


import collections ,random, string


alpha = list(string.ascii_letters)


lst_a = []

lst_b = []


for i in range(100):

    lst_a.append(alpha[random.choice(range(25))])

    lst_b.append(random.choice(range(1000)))



combine = dict(zip(lst_a,lst_b))

print(combine.get('a'))


update = list(zip(['a'],[2000]))

combine.update(update)


print(combine.get('a'))

例如,使用键“a”,这些值不是彼此之和。


慕村225694
浏览 89回答 1
1回答

aluckdog

你可以使用默认字典d = defaultdict(float)for a, b in list_of_pairs:    d[a] += bdesired_output = list(d.items())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python