LoginSignup
0
1

More than 3 years have passed since last update.

Python # ソート

Last updated at Posted at 2020-04-27

ソート

sortsorted

リストデータをソートするときに主に用いるのが、sortsortedである。元々の内容を変更することなくソートした結果だけを得たいときはsortedを用いれば良い。また、sortedはタプルやイテレータなどにも用いることができる。挙動の違いは以下。

a = [4, 6, 2, 8]
b = [5, 3, 9, 7, 1]

a.sort()
print(a)
print(sorted(b))
print(b)

実行結果

[2, 4, 6, 8]
[1, 3, 5, 7, 9]
[5, 3, 9, 7, 1]

reserved

reservedは逆順にソートしする際に用いる関数である。sortedメソッドのように、内容そのものは変更せずにソート後の結果だけを返す関数である。

a = [4, 6, 2, 8]
print(reserved(a))

実行結果

[8, 6, 4, 2]

(スライス指定子を用いた逆順ソート)
a = [4, 6, 2, 8]
print(sorted(a)[::-1])

実行結果

[8, 6, 4, 2]

0
1
5

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