Python3でのリストのソートについて
単純なリストのソート
list = [1,3,2,4]
list.sort()
print(list)
# [1, 2, 3, 4]
もしくはsorted()関数を使用
*sorted関数は元のリストに影響を与えない
list = [1,3,2,4]
print(sorted(list))
# [1, 2, 3, 4]
降順
list = [1,3,2,4]
list.sort(reverse=True)
print(list)
# [4, 3, 2, 1]
辞書型のソート
dict = {"a","c","d","b"}
print(sorted(dict))
# ['a', 'b', 'c', 'd']
リスト内辞書のソート(Key指定)
list_dict = [{"no":1,"name":"Devit"},{"no":4,"name":"Josh"},{"no":2,"name":"Sam"},{"no":3,"name":"Tom"}]
print(sorted(list_dict,key=lambda x:x["no"]))
# [{'name': 'Devit', 'no': 1}, {'name': 'Sam', 'no': 2}, {'name': 'Tom', 'no': 3}, {'name': 'Josh', 'no': 4}]
# 降順
print(sorted(list_dict,key=lambda x:x["no"],reverse=True))
# [{'name': 'Josh', 'no': 4}, {'name': 'Tom', 'no': 3}, {'name': 'Sam', 'no': 2}, {'name': 'Devit', 'no': 1}]