Pythonの便利な組み込み関数・テクニック集
enumerate()のように、Pythonにはデータ操作を効率的に行うための便利な組み込み関数やテクニックがたくさんあります。以下にいくつか紹介します:
enumerate()
# 元の配列
arr = [10, 5, 30, 15, 20]
# インデックスと値のペアを作成
indexed_arr = list(enumerate(arr)) # [(0, 10), (1, 5), (2, 30), (3, 15), (4, 20)]
zip() - 複数のイテラブルを同時に処理
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}点")
map() - イテラブルの各要素に関数を適用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
filter() - 条件に合う要素だけを抽出
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4, 6]
リスト内包表記 - コンパクトなリスト生成
# map+filterの代わりに一行で書ける
squared_evens = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]
collections.Counter - 要素の出現回数をカウント
from collections import Counter
text = "mississippi"
letter_counts = Counter(text) # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
most_common = letter_counts.most_common(2) # [('i', 4), ('s', 4)]
collections.defaultdict - デフォルト値を持つ辞書
from collections import defaultdict
# リストをデフォルト値とする辞書
groups = defaultdict(list)
for name, group in [("Alice", "A"), ("Bob", "B"), ("Charlie", "A")]:
groups[group].append(name)
# defaultdict(<class 'list'>, {'A': ['Alice', 'Charlie'], 'B': ['Bob']})
itertools モジュール - イテレーション用ツール
import itertools
# 組み合わせ
combinations = list(itertools.combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)]
# 直積
product = list(itertools.product([1, 2], ['a', 'b'])) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
# グループ化
data = [('A', 1), ('A', 2), ('B', 1), ('B', 2)]
for key, group in itertools.groupby(data, lambda x: x[0]):
print(key, list(group))
# A [('A', 1), ('A', 2)]
# B [('B', 1), ('B', 2)]
any() と all() - 条件チェック
numbers = [1, 2, 3, 4, 5]
any_even = any(x % 2 == 0 for x in numbers) # True
all_positive = all(x > 0 for x in numbers) # True
sorted() の高度な使い方
# 複数キーでのソート
students = [
{"name": "Alice", "grade": "A", "age": 22},
{"name": "Bob", "grade": "B", "age": 20},
{"name": "Charlie", "grade": "A", "age": 21}
]
# まずgradeで、次にageでソート
sorted_students = sorted(students, key=lambda x: (x["grade"], x["age"]))
functools.partial() - 関数の部分適用
from functools import partial
def power(base, exponent):
return base ** exponent
# 2乗する関数を作成
square = partial(power, exponent=2)
print(square(5)) # 25