概要(sorted は「並び替えた新しいリスト」を返す基本関数)
sorted は、リスト・タプル・文字列などの「反復可能なデータ」を並び替えて“新しいリスト”として返す組み込み関数です。元のデータは変更しません。基本構文は sorted(iterable, key=None, reverse=False)。reverse=True で降順、key に比較基準となる関数を渡せます。
nums = [5, 2, 9, 1]
print(sorted(nums)) # [1, 2, 5, 9]
print(sorted(nums, reverse=True)) # [9, 5, 2, 1]
Python基本の使い方と引数(ここが重要)
iterable・key・reverse の役割
- iterable は並び替え対象(リスト、タプル、文字列、辞書ビューなど)。
- key は「各要素から比較用の値を取り出す関数」。例:key=len なら“長さ”基準。
- reverse=True で降順。既定は False(昇順)です。
words = ["tea", "espresso", "latte"]
print(sorted(words, key=len)) # ['tea', 'latte', 'espresso']
print(sorted(words, key=str.lower)) # 大小を無視した並び替え
print(sorted(words, key=len, reverse=True))# 長さの降順
Pythonlist.sort との違い(“破壊的”か“非破壊”か)
- list.sort() はリストのメソッドで“元のリストを直接並べ替え”、戻り値は None。
- sorted() は“新しい並び替え済みリストを返し”、元データを変えない。リスト以外にも使えます。
nums = [3, 1, 4]
nums.sort() # nums が並び替えられる(戻り値 None)
print(nums) # [1, 3, 4]
nums = [3, 1, 4]
sorted_nums = sorted(nums) # 新しいリストを返す
print(nums, sorted_nums) # [3, 1, 4] [1, 3, 4]
Pythonよく使う並び替え(数値・文字列・辞書・タプル)
数値や文字列を並べる
数値は大小、文字列は辞書順(Unicode のコードポイント順)が既定。大小無視したいときは key=str.casefold や key=str.lower を使います。
names = ["taro", "Hanako", "JIRO"]
print(sorted(names)) # ['Hanako', 'JIRO', 'taro']
print(sorted(names, key=str.casefold)) # 大文字小文字を無視
Python辞書を値で並べる
辞書全体はそのままソートできないため、items() と key を組み合わせます。ペアのタプル (key, value) を値側で比較。
prices = {"coffee": 350, "tea": 280, "juice": 220}
print(sorted(prices.items(), key=lambda kv: kv[1])) # 値の昇順
print(sorted(prices.items(), key=lambda kv: kv[1], reverse=True)) # 値の降順
Pythonタプルの特定要素で並べる
タプルの n 番目要素を取り出して比較基準にすると読みやすいです。
pairs = [("coffee", 350), ("tea", 280), ("juice", 220)]
print(sorted(pairs, key=lambda p: p[1])) # 価格で並べる
Python重要ポイントの深掘り(key 設計・安定ソート・性能)
複合条件は“タプルキー”が簡潔
複数条件で並べたいときは、key が (第一条件, 第二条件, …) を返すようにします。辞書順で順に比較され、同値時のタイブレークも自然に書けます。
products = [
{"name": "coffee", "price": 350},
{"name": "tea", "price": 350},
{"name": "juice", "price": 220},
]
print(sorted(products, key=lambda p: (p["price"], p["name"])))
# 価格→名前の順に比較
Python“安定ソート”なので並び替えを重ねられる
Python の並び替えは安定(元の相対順を保つ)なので、まず第2条件で並べてから第1条件で並べる、といった段階的ソートが安全にできます。実務で柔軟な整列が可能になります。
items = [
{"cat": "A", "score": 10},
{"cat": "B", "score": 10},
{"cat": "A", "score": 5},
]
# 1) カテゴリで並べる → 2) スコアで並べる(相対順維持)
items = sorted(items, key=lambda x: x["cat"])
items = sorted(items, key=lambda x: x["score"])
Python計算量・効率と key のコスト
sorted は高度に最適化されたソート(Timsort)で、実務に十分高速。とはいえ key 関数は要素ごとに呼ばれるため“高コスト計算”なら事前に基準値を添えて一度だけ計算する(装飾してから剥がす)と効率的です。
files = ["file2.txt", "file10.txt", "file1.txt"]
decorated = [(int(f[4:-4]), f) for f in files]
print([f for _, f in sorted(decorated)])
Python実務での定番パターン(データ整形・表示・ランキング)
表示用に並び替えて“元データは保持”
レポートやUI表示に合わせて sorted で並べ替え、新しいリストだけ使います。元データはそのまま保存。
original = [{"name": "coffee", "price": 350},
{"name": "tea", "price": 280}]
display = sorted(original, key=lambda x: x["price"], reverse=True) # 高い順
Python値でランキング表示(降順)
値基準で sorted(…, reverse=True) を使うとランキングが直感的に書けます。
sales = {"coffee": 5, "tea": 1, "juice": 3}
for name, qty in sorted(sales.items(), key=lambda kv: kv[1], reverse=True):
print(name, qty)
Python文字列の長さ・大文字小文字無視などのカスタム基準
文字列処理では key=len、key=str.casefold が頻出。自然な並びを短いコードで実現できます。
names = ["Apple", "banana", "Cherry"]
print(sorted(names, key=str.casefold)) # 大文字小文字を無視
print(sorted(names, key=len)) # 長さ順
Python例題で身につける(定番から一歩先まで)
例題1:数値の昇順・降順
nums = [12, 3, 7, 2]
print(sorted(nums)) # [2, 3, 7, 12]
print(sorted(nums, reverse=True)) # [12, 7, 3, 2]
Python例題2:辞書の値で並べ替え(ランキング)
scores = {"math": 80, "eng": 70, "sci": 90}
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
# [('sci', 90), ('math', 80), ('eng', 70)]
Python例題3:複合キー(姓→名)
people = [{"last": "Sato", "first": "Hanako"},
{"last": "Sato", "first": "Taro"},
{"last": "Abe", "first": "Jiro"}]
print(sorted(people, key=lambda p: (p["last"], p["first"])))
Python例題4:安定ソートを重ねる
items = [{"cat": "A", "score": 5},
{"cat": "A", "score": 10},
{"cat": "B", "score": 5}]
items = sorted(items, key=lambda x: x["cat"])
items = sorted(items, key=lambda x: x["score"]) # 相対順を保持したまま
print(items)
Pythonまとめ
sorted は「元データを変えず、新しい並び替え済みリストを返す」関数。key で比較基準、reverse で昇降順を制御でき、list.sort とは“非破壊か破壊か”が根本的な違いです。安定ソートの性質を活かせば段階的な整列も安全に行えます。実務では、辞書の items と組み合わせて“値基準のランキング”、文字列の casefold や長さ基準、複合キーでの並び替えを覚えると、一気に整形・表示・分析が楽になります。
