📘
map()とfilter()の違い
1. map 関数
意味
- 「関数を iterable(反復可能オブジェクト)の全要素に適用する」関数。
- 新しい イテレータ を返す。
構文
map(function, iterable, ...)
-
function: 各要素に適用する関数 -
iterable: 適用対象(リスト、タプル、文字列など) - 複数の iterable を渡すと、関数は複数引数を受け取る。
基本例
nums = [1, 2, 3, 4]
result = map(lambda x: x * 2, nums)
print(list(result)) # [2, 4, 6, 8]
複数の iterable
a = [1, 2, 3]
b = [10, 20, 30]
result = map(lambda x, y: x + y, a, b)
print(list(result)) # [11, 22, 33]
関数を直接渡す
words = ["apple", "banana"]
result = map(str.upper, words)
print(list(result)) # ['APPLE', 'BANANA']
特徴
- 一度消費すると再利用できない(イテレータだから)。
- シンプルな変換なら リスト内包表記でも書ける。
[x*2 for x in nums] # リスト内包表記
2. filter 関数
意味
- 「条件に合う要素だけを選別する」関数。
- 戻り値が
True/Falseの判定関数を使う。
構文
filter(function, iterable)
-
function: 判定関数(Trueの要素だけ残る) -
iterable: 判定対象
基本例
nums = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, nums)
print(list(result)) # [2, 4, 6]
関数を渡す例
def is_long(word):
return len(word) > 5
words = ["apple", "banana", "cherry", "fig"]
print(list(filter(is_long, words))) # ['banana', 'cherry']
リスト内包表記との比較
[x for x in nums if x > 2]
➡ Pythonic にはリスト内包表記がよく使われる。
3. map と filter の違い
| 機能 | 役割 | 例 |
|---|---|---|
map |
要素を 変換する | [1,2,3] → [2,4,6] |
filter |
要素を 選別する | [1,2,3,4] → [2,4] |
例:
nums = [1, 2, 3, 4, 5]
mapped = list(map(lambda x: x*2, nums)) # [2, 4, 6, 8, 10]
filtered = list(filter(lambda x: x%2==0, nums)) # [2, 4]
4. map / filter の位置づけ
組み込み関数 (built-in functions)
-
map/filterは 組み込み関数。
→importなしで最初から使える。 -
len,sum,printなどと同じカテゴリ。 - 標準ライブラリのモジュール関数ではない。
Executor との関係
-
concurrent.futures.Executor抽象クラスにはmapメソッドがある。
from concurrent.futures import ThreadPoolExecutor
def square(x): return x*x
with ThreadPoolExecutor() as executor:
results = executor.map(square, [1,2,3,4])
print(list(results)) # [1, 4, 9, 16]
- これは 並列処理のための
map。 - 組み込みの
mapとは別物。
まとめ
-
map(func, iterable)
→ 要素を変換するイテレータを返す。 -
filter(func, iterable)
→ 条件を満たす要素だけ残すイテレータを返す。 - どちらも 組み込み関数で、import 不要。
- 実際の Python コードでは リスト内包表記が可読性の点で好まれる。
- 並列処理での
Executor.mapは別物(並列タスク用)。
Discussion