Skip to content

Instantly share code, notes, and snippets.

@tanish-kr
Forked from tatsunori-nishikori/list_operation.py
Created June 20, 2017 02:29
Show Gist options
  • Save tanish-kr/ec703fc9fcb2b2a96ce23e9e2145916b to your computer and use it in GitHub Desktop.
Save tanish-kr/ec703fc9fcb2b2a96ce23e9e2145916b 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