LoginSignup
15
18

More than 5 years have passed since last update.

【メモ】Python3 list sort

Last updated at Posted at 2015-04-13

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}]
15
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
18