我會創建一箇中間字典中的每個名稱映射到最高得分爲名稱,然後將其回類型的字典元組算賬:
>>> result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'xxx', 'score': 10L}, {'name':'yyy', 'score':20})
>>> from collections import defaultdict
>>> max_scores = defaultdict(int)
>>> for d in result:
... max_scores[d['name']] = max(d['score'], max_scores[d['name']])
...
>>> max_scores
defaultdict(<type 'int'>, {'xxx': 120L, 'yyy': 20})
>>> tuple({name: score} for (name, score) in max_scores.iteritems())
({'xxx': 120L}, {'yyy': 20})
注: 1)我已經加入{'name': 'yyy', 'score': 20}
到您的示例數據來顯示它使用具有多個名稱的元組。
2)我使用defaultdict,假設score的最小值爲零。如果分數可能爲負數,則需要將defaultdict(int)的int參數更改爲返回小於最小可能分數的數字的函數。
順便提一下,我懷疑擁有一個字典元組並不是你想要做的最好的數據結構。你是否考慮過替代方案,比如說有一個單詞,也許每個名字都有一個分數列表?
我認爲你找到了最高分,而不是每個獨特名字的最高分。 – Gabe 2010-09-08 07:25:01
@加貝,不,我找到每個獨特名稱的最高分數。我稍微修改了這個問題。一探究竟。 – user12345 2010-09-08 07:27:39
@加貝:你是對的......我被一個名字的存在誤導了。 – 2010-09-08 07:41:04