如何从分数列表中pythonicly创建高分字典

How to pythonicly create a dictionary of highscores from a list of scores

在 python 中,假设我有一个球员姓名和分数的键值对列表,如下所示:

[
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

我想从这个列表中提取这样的高分字典:

{
    'ABC': 300,
    'DON': 90,
    'JON': 205,
}

奖金问题:我如何创建一个这样的分数历史字典并维护原始列表中每个分数出现的顺序?

{
    'ABC': [129, 300]
    'DON': [90, 50]
    'JON': [205]
}

显然,使用 for 循环实现解决方案非常容易,但是最pythonic 的方法 是什么,即如何用list/dictionary理解?

找到有效的解决方案:

scores_list = [
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

scores_history_dict = { k1: [v2 for (k2, v2) in scores_list if k1 == k2] for (k1, v1) in scores_list }
print scores_history_dict

highscores_dict = { k1: max([v2 for (k2, v2) in scores_list if k1 == k2]) for (k1, v1) in scores_list }
print highscores_dict

有什么想法吗?有人有更 pythonic、更聪明的方法吗?

第二部分是非常标准的事情:

allscores = [
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

from collections import defaultdict
scores = defaultdict(list)
for key, val in allscores:
    scores[key].append(val)

对分数进行分组后,您只需获取每个列表的 max

>>> topscores = dict( (k, max(v)) for k, v in scores.items() )
>>> print(topscores)
{'ABC': 300, 'DON': 90, 'JON': 205}