存储为键值对的元组的总和值按键列出

Sum values of tuples stored as key value pair in list by key(存储为键值对的元组的总和值按键列出)
本文介绍了存储为键值对的元组的总和值按键列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个类似 [('a',2),('a',3),('b',3),('c',2),('b',4)]

我想对所有相似的键求和并得到 [('a',5),('c',2),('b',7)] 以任何顺序都可以.

I want to sum all similar keys and get [('a',5),('c',2),('b',7)] in any order is fine.

有没有比使用字典更好的方法来做到这一点.最好使用列表理解,例如 [i for j in a for ...]

Is there a better way to do this instead of using a dictionary. Preferably using list comprehension something like [i for j in a for ...]

>>> a = [('a',2),('a',3),('b',3),('c',2),('b',4)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i,j in a:
...   d[i] += j 
... 
>>> d
defaultdict(<type 'int'>, {'a': 5, 'c': 2, 'b': 7})
>>> zip(d.keys(),d.values())
[('a', 5), ('c', 2), ('b', 7)]

在 Python-3 中,最后一行需要 list(zip(d.keys(),d.values()))

In Python-3, the last line requires list(zip(d.keys(),d.values()))

推荐答案

这也可以用 itertools.groupby 在列表推导中,尽管您的方法看起来不错,并且始终使用列表推导并没有内在的好处.恕我直言,在没有其他问题的情况下对一两行额外的代码进行处理是徒劳的冒险.如果您希望进一步添加到任何计数中,将此结果保留为字典而不是列表也可能有意义 - 字典是更合适的结构.

This is feasible alternatively with itertools.groupby in a list comprehension, although your approach seems fine and there is no inherent benefit to always using list comprehensions. Getting worked up about an extra line or two of code with no further issues is a fruitless venture, IMHO. It may also make sense to maintain this result as a dictionary instead of a list in case you wish to further add to any of the counts - the dictionary is the more suitable structure.

使用 itertools.groupby 方法,您可以根据第一个元组元素对已排序的组求和.

Using the itertools.groupby approach, you are summing the sorted groups based on first tuple elements.

from itertools import groupby
from operator import itemgetter

my_list = [('a',2),('a',3),('b',3),('c',2),('b',4)]
first = itemgetter(0)
sums = [(k, sum(item[1] for item in tups_to_sum))
        for k, tups_to_sum in groupby(sorted(my_list, key=first), key=first)]

输出:

[('a', 5), ('b', 7), ('c', 2)]

<小时>

这显然也可以(并且可能更适合)作为字典理解

{(k, sum(item[1] for item in tups_to_sum))
            for k, tups_to_sum in groupby(sorted(my_list, key=first), key=first)}

这篇关于存储为键值对的元组的总和值按键列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)