首页 > 解决方案 > Python - 元组列表,在这种情况下具有相同第一个值的元组总和?

问题描述

li=[('name1', 5, 10), ('name2', 3, 2), ('name1', 6, 3)]

假设我有这种情况。在第一个位置以相同名称开头的地方,我想将第二个添加到第二个,将第三个添加到第三个。

期望的结果:

[('name1', 11, 13), ('name2', 3, 2)]

有谁知道我如何在 Python 中做到这一点?

标签: pythonlistdictionarytuples

解决方案


鉴于:

LoT=[('name1', 5, 10), ('name2', 3, 2), ('name1', 6, 3)]

您可以先使用 dict 来累积like标签:

di={}
for t in LoT:
    di.setdefault(t[0], []).append(t[1:])

>>> di
{'name1': [(5, 10), (6, 3)], 'name2': [(3, 2)]}

然后使用这些标签的总和创建一个新列表:

>>> [(k,)+tuple(map(sum, zip(*li))) for k,li in di.items()]
[('name1', 11, 13), ('name2', 3, 2)]
# the interesting thing here is the zip(*li) which rotates the list of tuples
# zip(*[(5, 10), (6, 3)]) => [(5, 6), (10, 3)]

或者,只保留一个运行总计:

di={}
for t in LoT:
    try:
        di[t[0]]=tuple(map(sum, zip(di[t[0]], t[1:])))
    except KeyError:
        di[t[0]]=t[1:]

然后将运行总字典转换为列表:

[(k,)+t for k,t in di.items()]
# same result

无论元组的长度如何,这些解决方案都有效。


推荐阅读