Help us understand the problem. What is going on with this article?

Python # ソート

ソート

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]

ktr_gun
情報系大学生の勉強用メモ・備忘録
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした