将记录分组并在组内计数

时间:2019-06-19 11:13:33

标签: python grouping

我有JSON格式的API数据。

{
    "players": [{
        "player_full_name": "ghny",

        "url": "...",

    }]
}

我需要按分区对所有记录进行分组,并获取玩家人数。

    players = json_response.get("players")


    # players = players("event")



    print(division)

1 个答案:

答案 0 :(得分:0)

如果您打算只计算玩家人数,则可以简单地将collections.Counter与生成器表达式一起使用。

from collections import Counter

... # process json to get an iterable named 'players'

Counter(player.get('division') for player in players)

如果需要保留结果以进行进一步处理,我建议您使用itertools.groupby或查看类似toolz库的东西,该库为groupby提供了更友好的api。

如果您打算坚持使用itertools.groupby,则需要执行以下操作:

player_division = lambda player: player.get('division') 
g = groupby(sorted(players, key=player_division), player_division)
players_by_division = {division: list(players) for division, players in g}

注意:必须对itertools.groupby的输入进行排序才能正常工作