この記事について:Pythonプログラミングで頻繁に使用される組み込み関数を用途別に分類し、実践的な使用例とともに詳しく解説します。初心者から中級者まで役立つPython関数の一覧として活用してください。
目次
1. はじめに|Python組み込み関数の重要性
Pythonの組み込み関数は、プログラムの実行環境に最初から用意されている関数群です。これらの関数はimport
文を使わずに直接使用でき、日常的なプログラミング作業を効率化する重要な役割を果たします。
Python組み込み関数を適切に活用することで、以下のメリットが得られます:
- コードの簡潔性と可読性の向上
- 処理速度の最適化(C言語で実装されているため高速)
- 外部ライブラリへの依存を減らした安定性
- 標準化されたAPIによる保守性の向上
本記事では、実務で特に頻繁に使用される30個の組み込み関数を厳選し、用途別に分類して詳しく解説します。
2. 用途別関数分類一覧
効率的な学習と実践のために、Python関数一覧を以下のカテゴリに分類しています:
カテゴリ | 主な用途 | 代表的な関数 |
---|---|---|
データ型・構造操作 | データの長さ、型確認、構造変更 | len(), type(), list(), tuple() |
数値計算・統計 | 数値の計算、統計処理 | sum(), min(), max(), abs() |
反復処理・列挙 | ループ処理、要素の列挙 | range(), enumerate(), zip() |
フィルタリング・変換 | 条件による絞り込み、データ変換 | filter(), map(), sorted() |
入出力・文字列 | データの入出力、文字列処理 | print(), input(), str(), repr() |
型変換・検証 | データ型の変換、値の検証 | int(), float(), bool(), isinstance() |
3. データ型・構造操作関数
データサイエンスやプログラミングにおいて、データの構造を理解し操作することは基本中の基本です。以下の関数群は日常的に使用される重要な機能を提供します。
3.1 len() - 長さ・要素数の取得
len(object)
機能:オブジェクトの長さ(要素数)を返す
戻り値:整数(int)
len()
関数は、リスト、タプル、文字列、辞書などの要素数を取得する際に使用します。データ分析では配列のサイズ確認やループ処理の制御に頻繁に使用されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# 基本的な使用例 numbers = [1, 2, 3, 4, 5] print(len(numbers)) # 出力: 5 text = "Hello, Python!" print(len(text)) # 出力: 14 # 辞書の要素数 data = {"name": "田中", "age": 30, "city": "東京"} print(len(data)) # 出力: 3 # 2次元リストの行数 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(len(matrix)) # 出力: 3(行数) print(len(matrix[0])) # 出力: 3(列数) |
3.2 type() - データ型の確認
type(object)
機能:オブジェクトの型を返す
戻り値:type オブジェクト
プログラムのデバッグや動的な型チェックに使用します。特にデータ分析では、予期しない型の変換が発生していないかを確認する際に重要です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# 様々なデータ型の確認 print(type(42)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("Hello")) # <class 'str'> print(type([1, 2, 3])) # <class 'list'> print(type({"a": 1})) # <class 'dict'> # 型の比較 value = 100 if type(value) == int: print("整数です") # isinstance()との使い分け print(isinstance(42, int)) # True(推奨) print(type(42) == int) # True |
3.3 list() / tuple() - データ構造の変換
list(iterable) / tuple(iterable)
機能:イテラブルオブジェクトをリスト/タプルに変換
戻り値:list / tuple オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# 文字列をリストに変換 text = "Python" char_list = list(text) print(char_list) # ['P', 'y', 't', 'h', 'o', 'n'] # タプルをリストに変換(変更可能にする) coordinates = (10, 20, 30) coord_list = list(coordinates) coord_list.append(40) print(coord_list) # [10, 20, 30, 40] # リストをタプルに変換(不変にする) mutable_data = [1, 2, 3, 4] immutable_data = tuple(mutable_data) print(immutable_data) # (1, 2, 3, 4) # range()オブジェクトをリストに変換 numbers = list(range(5)) print(numbers) # [0, 1, 2, 3, 4] |
4. 数値計算・統計関数
データサイエンスにおいて数値計算は中核的な処理です。以下の関数群は基本的な統計処理や数値操作を効率化します。
4.1 sum() - 合計値の計算
sum(iterable, start=0)
機能:イテラブルオブジェクトの要素の合計を計算
戻り値:数値(int, float)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# 基本的な合計計算 numbers = [1, 2, 3, 4, 5] total = sum(numbers) print(total) # 15 # 開始値を指定 result = sum(numbers, 10) print(result) # 25(10 + 1 + 2 + 3 + 4 + 5) # 浮動小数点数の合計 prices = [1.5, 2.3, 4.7, 3.2] total_price = sum(prices) print(f"合計金額: {total_price}") # 11.7 # リスト内包表記との組み合わせ squares = [x**2 for x in range(1, 6)] sum_of_squares = sum(squares) print(sum_of_squares) # 55(1 + 4 + 9 + 16 + 25) |
4.2 min() / max() - 最小値・最大値の取得
min(iterable) / max(iterable)
機能:イテラブルオブジェクトの最小値/最大値を返す
戻り値:要素の型に依存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# 基本的な最小値・最大値 scores = [85, 92, 78, 96, 88] print(f"最低点: {min(scores)}") # 78 print(f"最高点: {max(scores)}") # 96 # 複数の引数を直接指定 print(min(10, 5, 8, 3)) # 3 print(max(10, 5, 8, 3)) # 10 # 文字列の比較(辞書順) words = ["apple", "banana", "cherry", "date"] print(min(words)) # "apple" print(max(words)) # "date" # keyパラメータを使用した条件指定 students = [ {"name": "田中", "score": 85}, {"name": "佐藤", "score": 92}, {"name": "鈴木", "score": 78} ] best_student = max(students, key=lambda x: x["score"]) print(best_student) # {"name": "佐藤", "score": 92} |
4.3 abs() - 絶対値の取得
abs(number)
機能:数値の絶対値を返す
戻り値:数値(int, float)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# 整数の絶対値 print(abs(-5)) # 5 print(abs(5)) # 5 # 浮動小数点数の絶対値 print(abs(-3.14)) # 3.14 # 差の絶対値を計算 target = 100 current = 85 difference = abs(target - current) print(f"目標との差: {difference}") # 15 # 複素数の絶対値(距離) complex_num = 3 + 4j print(abs(complex_num)) # 5.0(√(3² + 4²)) |
4.4 round() - 四捨五入
round(number, ndigits=None)
機能:数値を指定した桁数で四捨五入
戻り値:数値(int, float)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# 基本的な四捨五入 print(round(3.14159)) # 3 print(round(3.6)) # 4 # 小数点以下の桁数を指定 print(round(3.14159, 2)) # 3.14 print(round(3.14159, 4)) # 3.1416 # 整数部分の四捨五入 print(round(1234.567, -1)) # 1230.0 print(round(1234.567, -2)) # 1200.0 # 計算結果の整形 price = 1234.5678 print(f"価格: {round(price, 2)}円") # 価格: 1234.57円 |
5. 反復処理・列挙関数
効率的なループ処理は、プログラムの性能と可読性を大きく左右します。以下の関数群は、様々な反復処理パターンを提供します。
5.1 range() - 連続した整数の生成
range(start, stop, step)
機能:連続した整数のシーケンスを生成
戻り値:range オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# 基本的な使用法 for i in range(5): print(i) # 0, 1, 2, 3, 4 # 開始値と終了値を指定 for i in range(1, 6): print(i) # 1, 2, 3, 4, 5 # ステップを指定 for i in range(0, 10, 2): print(i) # 0, 2, 4, 6, 8 # 逆順の生成 for i in range(5, 0, -1): print(i) # 5, 4, 3, 2, 1 # リストのインデックス取得 fruits = ["apple", "banana", "cherry"] for i in range(len(fruits)): print(f"{i}: {fruits[i]}") # リスト化 numbers = list(range(1, 11)) print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
5.2 enumerate() - インデックス付きの反復処理
enumerate(iterable, start=0)
機能:イテラブルオブジェクトにインデックスを付けて反復
戻り値:enumerate オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# 基本的な使用法 fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # 0: apple # 1: banana # 2: cherry # 開始インデックスを指定 for number, fruit in enumerate(fruits, start=1): print(f"{number}. {fruit}") # 1. apple # 2. banana # 3. cherry # 文字列の文字位置を取得 text = "Python" for pos, char in enumerate(text): print(f"位置{pos}: '{char}'") # 条件に合致するインデックスを取得 numbers = [10, 25, 30, 45, 50] even_indices = [i for i, num in enumerate(numbers) if num % 2 == 0] print(even_indices) # [0, 2, 4] |
5.3 zip() - 複数のイテラブルの並列処理
zip(*iterables)
機能:複数のイテラブルオブジェクトを並列に処理
戻り値:zip オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# 2つのリストを並列処理 names = ["田中", "佐藤", "鈴木"] scores = [85, 92, 78] for name, score in zip(names, scores): print(f"{name}: {score}点") # 3つ以上のイテラブル cities = ["東京", "大阪", "名古屋"] populations = [1400, 880, 230] areas = [2194, 1905, 326] for city, pop, area in zip(cities, populations, areas): density = pop / area print(f"{city}: 人口密度 {density:.2f}万人/km²") # 辞書の作成 keys = ["name", "age", "city"] values = ["田中", 30, "東京"] person = dict(zip(keys, values)) print(person) # {'name': '田中', 'age': 30, 'city': '東京'} # 転置(行列の行と列を入れ替え) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] transposed = list(zip(*matrix)) print(transposed) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)] |
6. フィルタリング・変換関数
データの選択、変換、並び替えは、データ処理の重要な操作です。以下の関数群は、関数型プログラミングの要素を取り入れた効率的なデータ処理を提供します。
6.1 filter() - 条件によるフィルタリング
filter(function, iterable)
機能:条件関数がTrueを返す要素のみを抽出
戻り値:filter オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# 偶数のみを抽出 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4, 6, 8, 10] # 空文字列を除去 words = ["apple", "", "banana", "", "cherry"] non_empty = list(filter(None, words)) print(non_empty) # ['apple', 'banana', 'cherry'] # 条件を満たすデータを抽出 students = [ {"name": "田中", "score": 85}, {"name": "佐藤", "score": 92}, {"name": "鈴木", "score": 78}, {"name": "高橋", "score": 95} ] # 90点以上の学生 high_scorers = list(filter(lambda s: s["score"] >= 90, students)) print(high_scorers) # 名前が3文字の学生 three_char_names = list(filter(lambda s: len(s["name"]) == 2, students)) print(three_char_names) |
6.2 map() - 一括変換処理
map(function, iterable)
機能:イテラブルの各要素に関数を適用
戻り値:map オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# 数値を2乗する numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x**2, numbers)) print(squares) # [1, 4, 9, 16, 25] # 文字列を大文字に変換 words = ["python", "java", "javascript"] upper_words = list(map(str.upper, words)) print(upper_words) # ['PYTHON', 'JAVA', 'JAVASCRIPT'] # 複数のイテラブルを同時に処理 numbers1 = [1, 2, 3, 4] numbers2 = [10, 20, 30, 40] sums = list(map(lambda x, y: x + y, numbers1, numbers2)) print(sums) # [11, 22, 33, 44] # 型変換 str_numbers = ["1", "2", "3", "4", "5"] int_numbers = list(map(int, str_numbers)) print(int_numbers) # [1, 2, 3, 4, 5] # 辞書の値を変換 prices = [{"item": "apple", "price": 100}, {"item": "banana", "price": 200}] with_tax = list(map(lambda x: {**x, "price_with_tax": x["price"] * 1.1}, prices)) print(with_tax) |
6.3 sorted() - ソート処理
sorted(iterable, key=None, reverse=False)
機能:イテラブルオブジェクトをソートした新しいリストを返す
戻り値:list オブジェクト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# 基本的なソート numbers = [3, 1, 4, 1, 5, 9, 2, 6] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 6, 9] # 逆順ソート reverse_sorted = sorted(numbers, reverse=True) print(reverse_sorted) # [9, 6, 5, 4, 3, 2, 1, 1] # 文字列のソート words = ["banana", "apple", "cherry", "date"] sorted_words = sorted(words) print(sorted_words) # ['apple', 'banana', 'cherry', 'date'] # 長さでソート sorted_by_length = sorted(words, key=len) print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry'] # 辞書のソート students = [ {"name": "田中", "score": 85}, {"name": "佐藤", "score": 92}, {"name": "鈴木", "score": 78} ] sorted_students = sorted(students, key=lambda x: x["score"], reverse=True) print(sorted_students) # 点数の高い順 # 複数条件でのソート data = [("apple", 100), ("banana", 150), ("apple", 120), ("cherry", 200)] sorted_data = sorted(data, key=lambda x: (x[0], x[1])) print(sorted_data) # 名前順、同じ名前なら価格順 |
7. 入出力・文字列関数
プログラムと外部との情報交換は、実用的なアプリケーション開発において不可欠です。以下の関数群は、基本的な入出力と文字列操作を提供します。
7.1 print() - 出力処理
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
機能:オブジェクトを標準出力に出力
戻り値:None
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# 基本的な出力 print("Hello, World!") # 複数の値を同時に出力 name = "田中" age = 30 print("名前:", name, "年齢:", age) # 区切り文字を指定 print("apple", "banana", "cherry", sep=", ") # 出力: apple, banana, cherry # 改行を制御 print("Loading", end="") for i in range(3): print(".", end="") print(" Done!") # 出力: Loading... Done! # フォーマット文字列 score = 85.5 print(f"あなたの得点は {score:.1f} 点です") # 複数行の文字列 message = """ こんにちは! 複数行の メッセージです。 """ print(message) |
7.2 input() - 入力処理
input(prompt='')
機能:標準入力からの文字列を取得
戻り値:文字列(str)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# 基本的な入力 name = input("お名前を入力してください: ") print(f"こんにちは、{name}さん!") # 数値の入力(型変換が必要) age = int(input("年齢を入力してください: ")) print(f"来年は {age + 1} 歳ですね") # 複数の値を一度に入力 data = input("名前と年齢をスペースで区切って入力: ").split() name, age = data[0], int(data[1]) # 入力値の検証 while True: try: score = float(input("点数を入力してください (0-100): ")) if 0 <= score <= 100: break else: print("0から100の間で入力してください") except ValueError: print("数値を入力してください") print(f"入力された点数: {score}") # CSVライクなデータの入力 numbers = list(map(int, input("数値をカンマ区切りで入力: ").split(","))) print(f"合計: {sum(numbers)}") |
7.3 str() / repr() - 文字列変換
str(object) / repr(object)
機能:オブジェクトの文字列表現を取得
戻り値:文字列(str)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# 基本的な文字列変換 number = 42 text = str(number) print(text) # "42" print(type(text)) # <class 'str'> # str()とrepr()の違い data = "Hello\nWorld" print(str(data)) # Hello(改行)World print(repr(data)) # 'Hello\nWorld' # リストの文字列表現 numbers = [1, 2, 3, 4, 5] print(str(numbers)) # [1, 2, 3, 4, 5] print(repr(numbers)) # [1, 2, 3, 4, 5] # 日時オブジェクトの文字列化 from datetime import datetime now = datetime.now() print(str(now)) # 2024-01-01 12:00:00.123456 print(repr(now)) # datetime.datetime(2024, 1, 1, 12, 0, 0, 123456) # デバッグでの使用 def debug_print(obj): print(f"str(): {str(obj)}") print(f"repr(): {repr(obj)}") debug_print("Hello\tWorld") debug_print([1, 2, 3]) |
8. 型変換・検証関数
動的型付け言語であるPythonにおいて、型の変換と検証は重要な操作です。以下の関数群は、安全で効率的な型操作を提供します。
8.1 int() / float() / bool() - 基本型変換
int(x, base=10) / float(x) / bool(x)
機能:値を整数、浮動小数点数、真偽値に変換
戻り値:int / float / bool
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# 文字列から数値への変換 str_num = "123" integer = int(str_num) floating = float(str_num) print(integer, type(integer)) # 123 <class 'int'> print(floating, type(floating)) # 123.0 <class 'float'> # 進数変換 binary = "1010" decimal = int(binary, 2) # 2進数として解釈 print(decimal) # 10 hex_value = "FF" decimal_from_hex = int(hex_value, 16) # 16進数として解釈 print(decimal_from_hex) # 255 # 真偽値変換 print(bool(0)) # False print(bool(1)) # True print(bool("")) # False print(bool("text")) # True print(bool([])) # False print(bool([1])) # True # エラーハンドリング付きの変換 def safe_int_conversion(value): try: return int(value) except ValueError: print(f"'{value}' を整数に変換できません") return None result = safe_int_conversion("abc") print(result) # None # 小数点以下の切り捨て print(int(3.14)) # 3 print(int(3.99)) # 3 print(int(-3.14)) # -3 |
8.2 isinstance() - 型の確認
isinstance(object, classinfo)
機能:オブジェクトが指定した型のインスタンスかを確認
戻り値:真偽値(bool)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# 基本的な型確認 value = 42 print(isinstance(value, int)) # True print(isinstance(value, str)) # False print(isinstance(value, float)) # False # 複数の型を同時に確認 mixed_value = 3.14 print(isinstance(mixed_value, (int, float))) # True # 関数内での型チェック def process_data(data): if isinstance(data, list): return sum(data) elif isinstance(data, str): return len(data) elif isinstance(data, (int, float)): return data * 2 else: return "未対応の型です" print(process_data([1, 2, 3])) # 6 print(process_data("Hello")) # 5 print(process_data(5)) # 10 print(process_data({"a": 1})) # 未対応の型です # 継承関係の確認 class Animal: pass class Dog(Animal): pass dog = Dog() print(isinstance(dog, Dog)) # True print(isinstance(dog, Animal)) # True(継承関係も認識) print(isinstance(dog, str)) # False |
8.3 all() / any() - 真偽値の一括判定
all(iterable) / any(iterable)
機能:すべて/いずれかの要素が真かを判定
戻り値:真偽値(bool)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# 基本的な使用法 numbers = [1, 2, 3, 4, 5] print(all(numbers)) # True(すべて真) print(any(numbers)) # True(いずれかが真) numbers_with_zero = [1, 2, 0, 4, 5] print(all(numbers_with_zero)) # False(0が偽) print(any(numbers_with_zero)) # True(0以外が真) # 条件チェック scores = [85, 92, 78, 96, 88] all_passed = all(score >= 60 for score in scores) any_excellent = any(score >= 95 for score in scores) print(f"全員合格: {all_passed}") # True print(f"優秀者あり: {any_excellent}") # True # 文字列の検証 passwords = ["password123", "12345", "securePass!"] all_secure = all(len(pwd) >= 8 for pwd in passwords) any_secure = any(len(pwd) >= 8 for pwd in passwords) print(f"すべて安全: {all_secure}") # False print(f"一部安全: {any_secure}") # True # 空のイテラブル print(all([])) # True(空集合は真) print(any([])) # False(空集合は偽) |
9. 高度な活用パターン
ここまで紹介したPython組み込み関数を組み合わせることで、より高度なデータ処理が可能になります。実際のプロジェクトでよく見られるパターンを紹介します。
9.1 データクリーニング
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# データの前処理パイプライン raw_data = [" apple ", "", "BANANA", "123", "cherry pie", None] # 1. 空値・None値の除去 cleaned_data = list(filter(None, raw_data)) print("Step 1:", cleaned_data) # 2. 文字列の正規化 normalized_data = list(map(str.strip, cleaned_data)) normalized_data = list(map(str.lower, normalized_data)) print("Step 2:", normalized_data) # 3. 数値データの除去 text_only = list(filter(lambda x: not x.isdigit(), normalized_data)) print("Step 3:", text_only) # 4. 単語のみを抽出(スペースを含まない) single_words = list(filter(lambda x: ' ' not in x, text_only)) print("Final:", single_words) # 一括処理版 def clean_data(data): return list(filter( lambda x: x and ' ' not in x and not x.isdigit(), map(str.lower, map(str.strip, filter(None, data))) )) result = clean_data(raw_data) print("一括処理結果:", result) |
9.2 統計処理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# 売上データの統計分析 sales_data = [ {"product": "商品A", "price": 1000, "quantity": 5}, {"product": "商品B", "price": 1500, "quantity": 3}, {"product": "商品C", "price": 800, "quantity": 7}, {"product": "商品D", "price": 2000, "quantity": 2}, {"product": "商品E", "price": 1200, "quantity": 4} ] # 各商品の売上計算 revenues = list(map(lambda x: x["price"] * x["quantity"], sales_data)) print("売上一覧:", revenues) # 統計値の計算 total_revenue = sum(revenues) average_revenue = total_revenue / len(revenues) max_revenue = max(revenues) min_revenue = min(revenues) print(f"総売上: {total_revenue:,}円") print(f"平均売上: {average_revenue:,.0f}円") print(f"最高売上: {max_revenue:,}円") print(f"最低売上: {min_revenue:,}円") # 最も売上の高い商品を特定 max_product = max(sales_data, key=lambda x: x["price"] * x["quantity"]) print(f"最高売上商品: {max_product['product']}") # 売上1000円以上の商品数 high_revenue_count = sum(1 for x in sales_data if x["price"] * x["quantity"] >= 1000) print(f"売上1000円以上の商品数: {high_revenue_count}") # 売上でソート sorted_by_revenue = sorted(sales_data, key=lambda x: x["price"] * x["quantity"], reverse=True) print("売上順ランキング:") for i, item in enumerate(sorted_by_revenue, 1): revenue = item["price"] * item["quantity"] print(f"{i}. {item['product']}: {revenue:,}円") |
9.3 データ変換と集計
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# 学生成績データの処理 student_grades = [ {"name": "田中", "math": 85, "english": 92, "science": 78}, {"name": "佐藤", "math": 90, "english": 88, "science": 95}, {"name": "鈴木", "math": 75, "english": 82, "science": 70}, {"name": "高橋", "math": 95, "english": 90, "science": 88} ] # 各生徒の平均点を計算 for student in student_grades: scores = [student["math"], student["english"], student["science"]] student["average"] = round(sum(scores) / len(scores), 1) # 平均点を表示 print("=== 学生別平均点 ===") for student in student_grades: print(f"{student['name']}: {student['average']}点") # 科目別の統計 subjects = ["math", "english", "science"] print("\n=== 科目別統計 ===") for subject in subjects: scores = [student[subject] for student in student_grades] print(f"{subject}:") print(f" 平均: {sum(scores) / len(scores):.1f}点") print(f" 最高: {max(scores)}点") print(f" 最低: {min(scores)}点") # 優秀者(平均90点以上)の抽出 excellent_students = list(filter(lambda x: x["average"] >= 90, student_grades)) print(f"\n優秀者(平均90点以上): {len(excellent_students)}名") for student in excellent_students: print(f" {student['name']}: {student['average']}点") # 成績順ソート sorted_students = sorted(student_grades, key=lambda x: x["average"], reverse=True) print("\n=== 成績順ランキング ===") for rank, student in enumerate(sorted_students, 1): print(f"{rank}位: {student['name']} ({student['average']}点)") # 全科目合格者(60点以上)の確認 all_subjects_passed = [] for student in student_grades: scores = [student["math"], student["english"], student["science"]] if all(score >= 60 for score in scores): all_subjects_passed.append(student["name"]) print(f"\n全科目合格者: {', '.join(all_subjects_passed)}") |
10. まとめ|実践での活用方法
本記事で紹介した30のPython組み込み関数は、データサイエンスから一般的なプログラミングまで、幅広い場面で活用できる強力なツールです。
重要なポイント:
- 組み込み関数は高速:C言語で実装されているため、自作関数より高速
- メモリ効率が良い:iterator オブジェクトを返すため、大量データでも効率的
- 可読性が向上:標準化された関数名で、コードが理解しやすい
- 保守性が高い:外部ライブラリに依存しない安定した実装
10.1 実践的な使い分け
用途 | 推奨関数 | 使用例 |
---|---|---|
データ量の確認 | len() | 配列サイズ、文字列長の取得 |
基本統計 | sum(), min(), max() | 売上合計、最高得点の算出 |
データ変換 | map(), filter() | 価格計算、条件絞り込み |
並列処理 | zip(), enumerate() | 複数データの同時処理 |
型安全性 | isinstance(), type() | 入力値の検証 |
10.2 パフォーマンス最適化のコツ
1 2 3 4 5 6 7 8 9 10 11 |
# ❌ 非効率な書き方 result = [] for i in range(len(data)): if data[i] > 0: result.append(data[i] * 2) # ✅ 効率的な書き方 result = list(map(lambda x: x * 2, filter(lambda x: x > 0, data))) # ✅ さらに読みやすい書き方(リスト内包表記) result = [x * 2 for x in data if x > 0] |
10.3 学習の次のステップ
これらの基本的なPython関数一覧を習得したら、以下のステップでスキルアップを図ることをお勧めします:
- itertools モジュール:より高度な反復処理
- functools モジュール:関数型プログラミング
- collections モジュール:特殊なデータ構造
- NumPy, Pandas:データサイエンス向けライブラリ
Python の組み込み関数は、プログラミングの基礎体力となる重要なスキルです。日常的に使用することで、より効率的で読みやすいコードを書けるようになります。
実践演習:本記事で紹介した関数を使って、実際のデータ(CSV ファイル、Web API のレスポンスなど)を処理してみましょう。理論だけでなく、実際に手を動かすことで、真の理解が深まります。
継続的な学習と実践を通じて、Python プログラミングのスキルを向上させていきましょう。