2016-03-21 25 views
0

我有一個列表的列表,如本:從列出的清單獲取總計並將其應用到一本字典

[['blah', 5], ['blah', 6], ['blah',7], ['foo', 5], ['foo', 7]] 

我想要做的就是創建詞典的列表,列表中的第一個索引是關鍵詞,第二個是運行總數。

最終結果必須是這個樣子:

[{'name': 'blah', 'total': 18}, {'name': 'foo', 'total': 12}] 
+4

你有沒有嘗試編碼這個了嗎?你能否展示你的嘗試並解釋什麼不適合你? – idjaw

回答

3

我會在這裏使用一個計數器:

from collections import Counter 

res = Counter() 
for k, v in data: 
    res.update({k: v}) 

print(res) 

輸出:

Counter({'blah': 18, 'foo': 12}) 

但如果你真的想要的你要求的輸出:

final = [{'name': k, 'total': v} for k, v in res.items()] 
print(final) 

輸出:

[{'total': 18, 'name': 'blah'}, {'total': 12, 'name': 'foo'}] 
+1

非常感謝!我真的從來沒有想過使用收藏,這是愚蠢的我。你的答案正是我所需要的。 –

0

你可以使用reduce遍歷所有元素,總結起來:

from functools import reduce 

lists = [['blah',5],['blah',6],['blah',7],['foo',5],['foo',7]] 

def count(total, item): 
    key, val = item[0], item[1] 
    if key not in total: 
    total[key] = 0 
    total[key] += val 
    return total 

totals = reduce(count, lists, {}) 
print(totals) 
相關問題