【Python入門】Pythonのsorted関数とは?使い方と活用方法を徹底解説(Python 3.11)

Python

はじめに

Pythonはシンプルで強力なプログラミング言語であり、データの操作や処理に優れています。その中でも、リストやタプルなどのデータを簡単に並び替えることができる sorted 関数は、非常に便利な機能のひとつです。本記事では、Python 3.11を対象に sorted 関数の基本から応用までを詳しく解説します。

sorted関数とは?

sorted 関数は、リストやタプルなどのイテラブル(反復可能なオブジェクト)を並び替えて、新しいリストとして返す組み込み関数です。元のデータを変更せず、新しい並び順のリストを取得できる点が特徴です。

sorted関数の基本構文

sorted 関数の基本的な構文は以下の通りです。

sorted(iterable, key=None, reverse=False)

引数の説明

  • iterable:並び替え対象のデータ(リスト、タプル、文字列など)
  • key(オプション):並び替えの基準となる関数を指定(デフォルトは None
  • reverse(オプション): True を指定すると降順に並び替え(デフォルトは False

sorted関数の使用例

数値リストの並び替え

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 出力: [1, 2, 5, 5, 6, 9]

文字列リストの並び替え

words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words)  # 出力: ['apple', 'banana', 'cherry']

sorted関数の応用例

key引数を使用した並び替え(文字列の長さ順)

words = ["banana", "apple", "cherry"]
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)  # 出力: ['apple', 'cherry', 'banana']

辞書のリストを値でソート

students = [{"name": "Alice", "score": 90},
            {"name": "Bob", "score": 75},
            {"name": "Charlie", "score": 85}]

sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
print(sorted_students)
# 出力: [{'name': 'Alice', 'score': 90}, {'name': 'Charlie', 'score': 85}, {'name': 'Bob', 'score': 75}]

カスタム関数を使用した並び替え

def custom_sort(value):
    return value % 3  # 3で割った余りを基準にソート

numbers = [10, 3, 6, 2, 8, 1]
sorted_custom = sorted(numbers, key=custom_sort)
print(sorted_custom)  # 出力: [3, 6, 10, 1, 2, 8]

まとめ

sorted 関数は、リストやタプルなどのデータを簡単に並び替えることができる便利な関数です。基本的な並び替えから、 key 引数を利用したカスタムソートまで、多様な使い方が可能です。Pythonでのデータ処理の効率を向上させるために、ぜひ sorted 関数を活用してください。