python - Python - 元组列表,在这种情况下具有相同第一个值的元组总和?
问题描述
li=[('name1', 5, 10), ('name2', 3, 2), ('name1', 6, 3)]
假设我有这种情况。在第一个位置以相同名称开头的地方,我想将第二个添加到第二个,将第三个添加到第三个。
期望的结果:
[('name1', 11, 13), ('name2', 3, 2)]
有谁知道我如何在 Python 中做到这一点?
解决方案
鉴于:
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
无论元组的长度如何,这些解决方案都有效。
推荐阅读
- macos - 如果我在 React Native 中开发,更新到 macOS Mojave 是否安全?
- vue.js - 在 Vue 中观察计算属性的反应性触发器
- python - 将函数应用于该函数不接受 NaN 的 pandas 列
- mysql - SQL从外表varchar生成外键ID?
- java - 我的 MediaPlayer 和过渡效果不起作用
- android - 如何多次停止启动活动
- command-line - 创建符号链接文件夹时遇到问题
- c# - 将 lerp 设置为随着时间的推移。在 MS
- python - ImportError:运行 pytest 时无法导入名称
- javascript - 我应该为电子商务和博客网站使用前端框架(如 react、Vue.js 等)还是原生 JavaScript?