https://qiita.com/yousuke_yamaguchi/items/23014a3c8d8beb8ba073
この記事は最終更新日から1年以上が経過しています。
リストの並び替えはsort
やsorted
でサクッと書けるが、辞書のリストの並び替えをすぐ忘れてしまうのでメモ。lambdaを使うのはわかっているのだが、なかなか記憶に定着しないので書いてみる。
まずは基本のsortとsorted
sort()は破壊的。
降順にしたいときはsort(reverse=True)
。
nums = [3, 1, 9, 6]
nums.sort()
print nums # [1, 3, 6, 9]
nums.sort(reverse=True)
print nums # [9, 6, 3, 1]
sorted()は非破壊的。
降順にしたいときはsorted(hoge_list, reverse=True)
。
nums_1 = [3, 1, 9, 6]
nums_2 = sorted(nums_1)
print nums_1 # [3, 1, 9, 6]
print nums_2 # [1, 3, 6, 9]
nums_3 = sorted(nums_1, reverse=True)
print nums_3 # [9, 6, 3, 1]
辞書の並び替えはlambdaを使う
items()
を使うのでタプルになる。sort()
は使えない。
keyで並び替えたいとき
score = {'kokugo': 33, 'sansuu': 85, 'eigo': 60}
score.sort() # AttributeError: 'dict' object has no attribute 'sort'
score_sorted = sorted(score.items(), key=lambda x:x[0])
print score_sorted # [('eigo', 60), ('kokugo', 33), ('sansuu', 85)]
valueで並び替えたいとき
score = {'kokugo': 33, 'sansuu': 85, 'eigo': 60}
score_sorted = sorted(score.items(), key=lambda x:x[1])
print score_sorted # [('kokugo', 33), ('eigo', 60), ('sansuu', 85)]
ここから本題。辞書のリスト
lambdaのreturn部分のindex指定を、ソートしたいkeyにするだけ。
scores = [
{'kokugo': 33, 'sansuu': 85},
{'kokugo': 77, 'sansuu': 23},
{'kokugo': 55, 'sansuu': 100}
]
scores_sorted = sorted(scores, key=lambda x:x['kokugo'])
print scores_sorted
# [
# {'kokugo': 33, 'sansuu': 85},
# {'kokugo': 55, 'sansuu': 100},
# {'kokugo': 77, 'sansuu': 23}
# ]
'C Lang > Python Program Diary' 카테고리의 다른 글
파이선 Selenium으로 스크래핑 기초 (0) | 2021.01.21 |
---|---|
pyenv로 python인스톨 후 pipenv로 가상환경 관리하기 (0) | 2020.02.06 |
로그 가이드라인 (0) | 2019.11.21 |
pyenv 정리 (0) | 2019.11.18 |
파이썬 언더스코어(_)에 대하여 (0) | 2019.11.14 |