LoginSignup
1
3

More than 3 years have passed since last update.

Pythonのsort()メソッド

Posted at

はじめに

Pythonのsort()メソッドについて学んだのでメモ。

sort()メソッドとは

リストの並び替えを行うメソッド。
昇順・降順に並び替えられ、ソート順をカスタマイズすることもできる。

リストを昇順にソートする

sort()は引数なしの場合デフォルトで昇順にソートする。
要素が数値の場合は小さい順に、要素が文字列の場合は文字コードの順にソートする。

使い方
#リストLを昇順に並び替える
L.sort()
hight = [48, 65, 53, 90, 60]
hight.sort()
print(hight) # => [48, 53, 60, 65, 90]

fruits = ['banana', 'peach', 'apple', 'orange']
fruits.sort()
print(fruits)# =>['apple', 'banana', 'orange', 'peach']

リストを降順にソートする

reverseという引数を使うことで降順にソートできる。(デフォルトの値は'Falth')
要素が数値の場合は大きい順に、要素が文字列の場合は文字コードの逆順にソートする。

使い方
#リストLを降順にソートする
L.sort(reverse = True)
hight = [48, 65, 53, 90, 60]
hight.sort(reverse = True)
print(hight) # => [90, 65, 60, 53, 48]


fruits = ['banana', 'peach', 'apple', 'orange']
fruits.sort()
print(fruits)# =>['peach', 'orange', 'banana', 'apple']

ソート順をカスタマイズする

ソート順をカスタマイズするには、sort()にkeyという引数を与える。

使い方
#リストLをkeyで与えた関数でソートする
L.sort(key, reverse)
#名前とそれぞれの3教科のテストの点数のタプルのリストを作成する。
test_data = [("田中", 80, 67, 76), ("佐藤", 90, 67, 55), ("鈴木", 90, 70, 71)]

#テストの合計点を計算すし、その合計点の降順にソートする。
def sum_test_data(sub):
    return sub[1] + sub[2] + sub[3]
test_data.sort(key = sum_test_data, reverse = True)

print(sum_test_data(test_data[0])) # => 231(田中の合計点)
print(sum_test_data(test_data[1])) # => 223(佐藤の合計点)
print(sum_test_data(test_data[2])) # => 212(鈴木の合計点)
print(test_data) # => [('鈴木', 90, 70, 71), ('田中', 80, 67, 76), ('佐藤', 90, 67, 55)]

参考文献

Python3.7.4 ソート HOW TO

1
3
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
1
3