LoginSignup
0
1

【Python】多次元リストのソート

Posted at

一つのキーでソート

昇順にソート

0番目の要素で昇順にして並び替えます。

main.py
score = [[80, 65], [77, 45], [10, 99], [100, 100], [85, 43]]
score = sorted(score, key=lambda x: x[0])
print(score)
>> [[10, 99], [77, 45], [80, 65], [85, 43], [100, 100]]

降順にソート

0番目の要素で降順にして並び替えます。

main.py
score = [[80, 65], [77, 45], [10, 99], [100, 100], [85, 43]]
score = sorted(score, key=lambda x: x[0], reverse=True)
print(score)
>> [[100, 100], [85, 43], [80, 65], [77, 45], [10, 99]]

複数のキーでソート

昇順にソート

0番目と2番目の要素で昇順に並び替えます。

main.py
score = [[80, 65, 75], [77, 45, 95], [77, 99, 65], [100, 100, 0], [85, 43, 20]]
score = sorted(score, key=lambda x: (x[0], x[2]))
print(score)
>> [[77, 99, 65], [77, 45, 95], [80, 65, 75], [85, 43, 20], [100, 100, 0]]

昇順と降順にソート

0番目の要素を昇順、2番目の要素を降順にして並び替えます。
reverseを使ってしまうと、キーの要素で全て降順になってしまうので、降順にしたい要素には-をつけます。

main.py
score = [[80, 65, 75], [77, 45, 95], [77, 99, 65], [100, 100, 0], [85, 43, 20]]
score = sorted(score, key=lambda x: (x[0], -x[2]))
print(score)
>> [[77, 45, 95], [77, 99, 65], [80, 65, 75], [85, 43, 20], [100, 100, 0]]

このように、一つの要素を昇順で、もう一つの要素を降順に並び替える方法の記事が中々見つからなくて苦労しました。

参考文献

0
1
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
0
1