LoginSignup
2
3

More than 1 year has passed since last update.

【完全保存版】Python 要素の並べ替えについてあれこれ

Posted at

Pythonには、リストやタプルなどの要素を並べ替えるための多くのメソッドや関数があります。以下にいくつかの一般的なメソッドとそれらの使用例を示します。

sorted()関数:

sorted()関数は、リストやイテラブルなオブジェクトを受け取り、新しい並べ替えられたリストを返します。

Python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 1, 2, 3, 4, 5, 5, 6, 9]

sort()メソッド:

sort()メソッドは、リストオブジェクトに対して直接呼び出すことができます。元のリストを直接変更して並べ替えます。

Python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 5, 6, 9]

reverse引数

sorted()関数やsort()メソッドでは、reverse引数を使用して逆順に並べ替えることもできます。

Python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # [9, 6, 5, 5, 4, 3, 2, 1, 1]

numbers.sort(reverse=True)
print(numbers)  # [9, 6, 5, 5, 4, 3, 2, 1, 1]

key引数

sorted()関数やsort()メソッドでは、key引数を使用して並べ替えの基準を指定することもできます。key引数には関数を指定し、その関数が返す値に基づいて並べ替えが行われます。

Python
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=len)
print(sorted_fruits)  # ['date', 'apple', 'banana', 'cherry']

fruits.sort(key=str.lower)
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

sort()メソッドとlambda関数:

sort()メソッドには、lambda関数を使用して並べ替えの基準を指定することもできます。

Python
fruits = ["apple", "banana", "cherry", "date"]
fruits.sort(key=lambda x: x[1])  # 2番目の文字で並べ替え
print(fruits)  # ['banana', 'date', 'cherry', 'apple']

itemgetter()関数:

operatorモジュールのitemgetter()関数を使用すると、辞書やオブジェクトの特定のキーを基準にして並べ替えができます。

Python
from operator import itemgetter

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 18},
    {"name": "Charlie", "age": 22}
]

sorted_students = sorted(students, key=itemgetter("age"))
print(sorted_students)
# [{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 22}]

numpyモジュールのsort()関数

numpyモジュールを使用して、NumPy配列を並べ替えることもできます。

Python
import numpy as np

numbers = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])
sorted_numbers = np.sort(numbers)
print(sorted_numbers)  # [1 1 2 3 4 5 5 6 9]

operatorモジュールのattrgetter()関数

operatorモジュールのattrgetter()関数を使用すると、オブジェクトの属性を基準にして並べ替えることができます。

Python
from operator import attrgetter

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [
    Person("Alice", 25),
    Person("Bob", 18),
    Person("Charlie", 30)
]

sorted_people = sorted(people, key=attrgetter("age"))
for person in sorted_people:
    print(person.name, person.age)
# Bob 18
# Alice 25
# Charlie 30

heapqモジュールのheapify()関数とheappop()関数

heapqモジュールを使用すると、ヒープデータ構造を利用した効率的な並べ替えが可能です。

Python
import heapq

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
heapq.heapify(numbers)  # ヒープ化

sorted_numbers = []
while numbers:
    sorted_numbers.append(heapq.heappop(numbers))

print(sorted_numbers)  # [1, 1, 2, 3, 4, 5, 5, 6, 9]

pandasライブラリのsort_values()メソッド:

pandasライブラリを使用すると、データフレームの列やインデックスを基準にして並べ替えを行うことができます。

Python
import pandas as pd

data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 18, 30]
}

df = pd.DataFrame(data)
sorted_df = df.sort_values(by="Age")
print(sorted_df)
#      Name  Age
# 1     Bob   18
# 0   Alice   25
# 2  Charlie   30

operatorモジュールのmethodcaller()関数

operatorモジュールのmethodcaller()関数を使用すると、オブジェクトのメソッドを呼び出して並べ替えることができます。

Python
from operator import methodcaller

strings = ["apple", "banana", "cherry", "date"]
sorted_strings = sorted(strings, key=methodcaller("upper"))
print(sorted_strings)  # ['apple', 'banana', 'cherry', 'date']

functoolsモジュールのcmp_to_key()関数

functoolsモジュールのcmp_to_key()関数を使用すると、比較関数をキーコンバータ関数に変換して並べ替えに使用できます。

Python
from functools import cmp_to_key

def compare_length(a, b):
    if len(a) < len(b):
        return -1
    elif len(a) > len(b):
        return 1
    else:
        return 0

strings = ["apple", "banana", "cherry", "date"]
sorted_strings = sorted(strings, key=cmp_to_key(compare_length))
print(sorted_strings)  # ['date', 'apple', 'cherry', 'banana']

numpyモジュールのargsort()関数

numpyモジュールのargsort()関数を使用すると、NumPy配列の値のインデックスを並べ替えることができます。

Python
import numpy as np

numbers = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])
sorted_indices = np.argsort(numbers)
sorted_numbers = numbers[sorted_indices]
print(sorted_numbers)  # [1 1 2 3 4 5 5 6 9]

operatorモジュールのitemgetter()関数とattrgetter()関数の複数キー並べ替え

operatorモジュールのitemgetter()関数やattrgetter()関数を使用して、複数のキーに基づいて並べ替えを行うことができます。

Python
from operator import itemgetter

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 18},
    {"name": "Charlie", "age": 22},
    {"name": "Alice", "age": 25}
]

sorted_students = sorted(students, key=itemgetter("name", "age"))
print(sorted_students)
# [{'name': 'Alice', 'age': 20},
#  {'name': 'Alice', 'age': 25},
#  {'name': 'Bob', 'age': 18},
#  {'name': 'Charlie', 'age': 22}]

pandasライブラリのsort_values()メソッドと複数カラム並べ替え:

pandasライブラリのsort_values()メソッドを使用して、複数のカラムに基づいてデータフレームを並べ替えることができます。

Python
import pandas as pd

data = {
    "Name": ["Alice", "Bob", "Charlie", "Alice"],
    "Age": [25, 18, 30, 22],
    "Grade": [A, B, B, A]
}

df = pd.DataFrame(data)
sorted_df = df.sort_values(by=["Name", "Age"])
print(sorted_df)
#       Name  Age Grade
# 0    Alice   25     A
# 3    Alice   22     A
# 1      Bob   18     B
# 2  Charlie   30     B

numpyモジュールのlexsort()関数:

numpyモジュールのlexsort()関数を使用すると、複数の配列に基づいて値を並べ替えることができます。

Python
import numpy as np

name = np.array(["Alice", "Bob", "Charlie", "Alice"])
age = np.array([25, 18, 30, 22])

sorted_indices = np.lexsort((name, age))
sorted_name = name[sorted_indices]
sorted_age = age[sorted_indices]

print(sorted_name)  # ['Alice' 'Alice' 'Bob' 'Charlie']
print(sorted_age)  # [22 25 18 30]

最後に

これらは、Pythonで値を並べ替えるためのさまざまな手法の一部です。データや要件に合わせて、適切な方法を選択して使用してください。

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