基于元组第一个值的python求和元组列表

标签 python list sum

假设我有以下列表元组:

myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]

我想根据相同的第一个元组值对这个列表求和:

[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z

对于 myList

sum = 2*5 + 3*6 = 28

我怎样才能得到这个?

最佳答案

你可以使用collections.defaultdict:

>>> from collections import defaultdict
>>> from operator import mul
>>> lis = [(0,2),(1,3),(2,4),(0,5),(1,6)]
>>> dic = defaultdict(list)
>>> for k,v in lis:
    dic[k].append(v)  #use the first item of the tuple as key and append second one to it
...     

#now multiply only those lists which contain more than 1 item and finally sum them.
>>> sum(reduce(mul,v) for k,v in dic.items() if len(v)>1)
 28

关于基于元组第一个值的python求和元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16643514/

相关文章:

sql - 具有空值的外部连接表的累积和

python - 如何创建包含 threading.Event 和 multiprocessing.Event 的协议(protocol)?

python - setuptools 应该在 setup.cfg 文件的 setup_requires 条目中吗?

python - 删除列表中的元素

python - 将列表列表保存到另一个列表列表中,但在 python 中进行了更改

Mysql Update with table joins - 用另一个表字段的总和更新一个表的字段

python - 在Python中,isinstance()可以用来检测类方法吗?

python - 比较两个列表并打印出不相等的元素

java - 仅使用 java 8 lambda 将 List<Object> 转换为 List<List<String>>

matlab - 添加带有 NaN 的 2x2 矩阵