Python sorted() ビルトイン関数
イテラブルの要素から新しいソート済みリストを返します。
Introduction
sorted() 関数は、イテラブルの要素から新しいソート済みリストを返します。元のイテラブルは変更されません。
reverse パラメータを使用して、降順にソートすることもできます。
Examples
数値のリストのソート:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
[1, 1, 2, 3, 4, 5, 6, 9]
文字列のリストのソート:
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words)
['apple', 'banana', 'cherry']
逆順のソート:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)
[9, 6, 5, 4, 3, 2, 1, 1]