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.

リストの並べ替え、sort()とsorted()

Last updated at Posted at 2023-06-02

リストの中身を昇順や降順に並べ替える時に使うsort関数とsorted関数

sort関数は破壊的処理(元の要素自体を書き換える処理)を行う

num_list = [4, 5, 6, 2, 1, 7, 8, 3, 5, 0, 2, 6, 3]

num_list.sort()
print(num_list)
# [0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8]

引数をreverse = Trueにすると降順となる

num_list = [4, 5, 6, 2, 1, 7, 8, 3, 5, 0, 2, 6, 3]

num_list.sort(reverse = True)
print(num_list)
# [8, 7, 6, 6, 5, 5, 4, 3, 3, 2, 2, 1, 0]

続いてsorted関数
こちらは破壊的処理は行わず、書き方も変わる

num_list = [4, 5, 6, 2, 1, 7, 8, 3, 5, 0, 2, 6, 3]

sort_num_list = sorted(num_list)
print(sort_num_list)
# [0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8]

こちらもsort同様、降順にできる

num_list = [4, 5, 6, 2, 1, 7, 8, 3, 5, 0, 2, 6, 3]

sort_num_list = sorted(num_list,reverse = True)
print(sort_num_list)
# [8, 7, 6, 6, 5, 5, 4, 3, 3, 2, 2, 1, 0]

また、sorted関数は文字列にも使える

abc_list = ['c', 'e', 'a', 'b', 'd']

sort_abc_list = sorted(abc_list)
reverse_sort_abc_list = sorted(abc_list, reverse = True)

print(sort_abc_list)
print(reverse_sort_abc_list)
# ['a', 'b', 'c', 'd', 'e']
# ['e', 'd', 'c', 'b', 'a']

また、文字列リストもソート可能

str_list = ['lion', 'tiger', 'dog', 'cat', 'bard']

sort_str_list = sorted(str_list)
reverse_sort_str_list = sorted(str_list, reverse = True)

print(sort_str_list)
print(reverse_sort_str_list)
# ['bard', 'cat', 'dog', 'lion', 'tiger']
# ['tiger', 'lion', 'dog', 'cat', 'bard']

そしてリストの中の要素として文字列を扱う場合は、文字列そのものではないためsortも使用可能

str_list = ['lion', 'tiger', 'dog', 'cat', 'bard']

str_list.sort()
print(str_list)
# ['bard', 'cat', 'dog', 'lion', 'tiger']
0
0
1

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?