問題描述
我有一個類似 [('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)}
這篇關于存儲為鍵值對的元組的總和值按鍵列出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!