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?

More than 1 year has passed since last update.

Pythonでソート

Last updated at Posted at 2022-02-23

#並べ替えたい

##sortを使う
###昇順

l  = [1, 2, 3, 5, 4, 8]
l.sort()
l
[1, 2, 3, 4, 5, 8]

###降順

l  = [1, 2, 3, 5, 4, 8]
l.sort(reverse=True)
l
[8, 5, 4, 3, 2, 1]

sort()はタプルに対しては使えない。sort()を使うと元のリストが書き換えられる。

##sortedを使う

l  = [2, 1, 3, 5, 4, 8]
sorted(l), l
([1, 2, 3, 4, 5, 8], [2, 1, 3, 5, 4, 8])

元のリストはそのまま。sorted()は文字列やタプルを引数にできるが、返すのはリスト。

##itemgetterでリスト内のリストを並べ替え

from operator import itemgetter

ll = [["acd", 123, 456], ["bfe", 234, 102], ["edo", 132, 9]]
print(
    sorted(ll, key=itemgetter(0)),
    sorted(ll, key=itemgetter(1)),
    sorted(ll, key=itemgetter(2)),
    sep = "\n"
    )
[['acd', 123, 456], ['bfe', 234, 102], ['edo', 132, 9]]
[['acd', 123, 456], ['edo', 132, 9], ['bfe', 234, 102]]
[['edo', 132, 9], ['bfe', 234, 102], ['acd', 123, 456]]

itemgetter()の括弧内でどれで並べ替えするか決められる。
from operator import itemgetter

ll = [["acd", 123, 456], ["bfe", 234, 102], ["edo", 132, 9], ["bfe", 120, 2]]
print(
    sorted(ll, key=itemgetter(0, 1)),
    sorted(ll, key=itemgetter(0)),
    sep = "\n"
)
[['acd', 123, 456], ['bfe', 120, 2], ['bfe', 234, 102], ['edo', 132, 9]]
[['acd', 123, 456], ['bfe', 234, 102], ['bfe', 120, 2], ['edo', 132, 9]]

itemgetter(n, m)とすれば2段階でソートできる。(nが優先、mが第二段階)

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?