Skip to content

Instantly share code, notes, and snippets.

@tatsunori-nishikori
Created June 2, 2017 06:08
Show Gist options
  • Save tatsunori-nishikori/5fe96b46dc19f562f9af69b74ddf3d74 to your computer and use it in GitHub Desktop.
Save tatsunori-nishikori/5fe96b46dc19f562f9af69b74ddf3d74 to your computer and use it in GitHub Desktop.
Python list operation
# -*- coding: utf-8 -*-
from itertools import groupby
score = [
{ "id": 1, "name": "アリス", "class": "1-A", "score": 92 },
{ "id": 2, "name": "カレン", "class": "1-B", "score": 43 },
{ "id": 3, "name": "しの", "class": "1-A", "score": 21 },
{ "id": 4, "name": "あやや", "class": "1-A", "score": 94 },
{ "id": 5, "name": "よーこ", "class": "1-A", "score": 38 }
]
# groupby(クラス別にグルーピング)
class_group = groupby(score, lambda r:r["class"])
# sort(スコア降順)
score_map = {}
for dept, item in class_group:
# groupbyオブジェクトは一度iterationさせると消える
class_map[dept] = sorted(item, key=lambda x:x["score"], reverse=True)
print class_map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment