0
1

More than 3 years have passed since last update.

Pythonでソートする時のテクニック

Posted at

はじめに

Python3で競プロをしているときにソートの方法をド忘れすることがあるのでメモ

以下、インタプリタモードで実行しているため、行の最初に >>>> がついているものは入力だと思って見てほしい。

list.sort() と sorted(list) の違い

list.sort() は元のリストをソートする。返り値は None

>>>> list = [2, 3, 5, 1, 4]
>>>> list.sort()
>>>> list
[1, 2, 3, 4, 5]

sorted(list) は元のリストは変更せずにソートした結果を返す

>>>> list = [2, 3, 5, 1, 4]
>>>> sorted(list)
[1, 2, 3, 4, 5]
>>>> list
[2, 3, 5, 1, 4]

逆順にソートしたい時

以下、 list.sort() でも sorted(list) でも同じオプションを使うので sorted(list) のみ扱う

オプションで reverse=True を指定する

>>>> list = [2, 3, 5, 1, 4]
>>>> sorted(list)
[1, 2, 3, 4, 5]
>>>> sorted(list, reverse=True)
[5, 4, 3, 2, 1]

ソートに使う列を限定したい時

普通にソートすると左の列から順にソートする。辞書順のようなイメージ

>>>> people = [('Bob', 12), ('Alice', 10), ('Chris', 8), ('Chris', 7)]
>>>> sorted(people)
[('Alice', 10), ('Bob', 12), ('Chris', 7), ('Chris', 8)]

2列目のみをソートに使いたい時

>>>> sorted(people, key=lambda x:x[1])
[('Chris', 7), ('Chris', 8), ('Alice', 10), ('Bob', 12)]

1, 2列目をソートに使いたい時

>>>> sorted(people, key=lambda x:(x[0], x[1]))
[('Alice', 10), ('Bob', 12), ('Chris', 7), ('Chris', 8)]

おわりに

itemgetter, attrgetterを使えばラムダ式を書かなくて済むが、覚えることが増えるので自分は使わないことにした。

使いたい方は参考のリンクから確認してほしい。

参考

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