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

【Python初心者】ソートに使える組み込み関数の使い方まとめ

Posted at

よく使うソートに関する組み込み関数の使い方をまとめました。
初学者の自分が学習中に整理した内容なので、同じく勉強中の方の参考になればと思います。

sorted() の使い方

sorted() はイテラブルを昇順(または降順)に並べ替えて、新しいリストとして返してくれる関数です。

numbers = [3, 1, 4, 1, 5]
result = sorted(numbers)
print(result)  # [1, 1, 3, 4, 5]

元のリストは変更されません。

print(numbers)  # [3, 1, 4, 1, 5]

reverse=True を使って降順にする

sorted(numbers, reverse=True)  # [5, 4, 3, 1, 1]

key 引数の使い方

key を使うと、ソートの基準を関数で指定できます。

words = ["banana", "apple", "grape"]
sorted(words, key=len)  # ['apple', 'grape', 'banana']

len 関数を指定すると、文字列の長さでソートされます。

operator モジュールと itemgetter

辞書のリストなどをソートしたいときは operator.itemgetter() を使うと便利です。

from operator import itemgetter

fruits = [
    {"name": "apple", "price": 100},
    {"name": "banana", "price": 80},
    {"name": "grape", "price": 120}
]

sorted(fruits, key=itemgetter("price"))

実行結果:

[{'name': 'banana', 'price': 80}, {'name': 'apple', 'price': 100}, {'name': 'grape', 'price': 120}]

reversed() の使い方

reversed() は元のイテラブルを逆順に並べた イテレータ を返します。

numbers = [1, 2, 3]
rev = reversed(numbers)
print(list(rev))  # [3, 2, 1]

reversed() の戻り値はイテレータなので、list() で明示的にリスト化する必要があります。

zip() の使い方

複数のイテラブルをまとめて、対応する要素をペアにして返します。

names = ["apple", "banana", "grape"]
prices = [100, 80, 120]

for name, price in zip(names, prices):
    print(name, price)

実行結果:

apple 100
banana 80
grape 120

リストなどに変換して使うこともできます。

list(zip(names, prices))  # [('apple', 100), ('banana', 80), ('grape', 120)]

おわりに

今回の記事では sorted()zip() など、Pythonでよく使われる基本関数やソートの書き方をまとめました。
key=operator.itemgetter は最初は戸惑いましたが、慣れてくると柔軟なデータ処理ができるようになってきました。

1
0
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
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?