0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonのlistを重複削除してソートするならsorted(set(list))がいいですよ

Posted at

pythonのlistを重複削除してソートする

a = [3, 1, 2, 2, 3]

これを

b = [1, 2, 3]

こうしたい。

解法

b = sorted(set(a))

list(set(a)).sort()はNoneを返す

listをソートするにはsortedの他にsortというのもあります。それを使ってlist(set(a)).sort()と書いてみるとうまく動かなかったという話です。

ChatGPTに理由を聞いてみたんですがよくわかりません。ChatGPT曰く、

list(set(a)).sort() が None を返す理由は、
list(set(a)) が 一時的に作られたリストであり、
そのリストに対して .sort() を インプレース(その場)で実行し、
戻り値は常に None だからです。

どうしてもsortを使いたいときは以下のようにすると良いです。

b = list(set(a))
b.sort()
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?