Python3 エンジニア認定基礎試験 練習問題 Day27:組み込み関数(map, filter, reduce)

【本日のミッション】

Day26では「組み込み関数(enumerate, zip)」を学びました。

今日は map(), filter(), reduce() を使って、データ処理を効率化する方法を学びましょう。

map の基本

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares)

出力結果

[1, 4, 9, 16]

map() は各要素に関数を適用して、新しいリストを作ります。

filter の基本

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)

出力結果

[2, 4, 6]

filter() は条件を満たす要素だけを取り出します。

reduce の基本

from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total)

出力結果

10

reduce() は累積的に関数を適用して、1つの値にまとめます。

練習問題

次のコードを実行するとどうなるでしょうか?

from functools import reduce

nums = [1, 2, 3, 4, 5]

print(list(map(lambda x: x*2, nums)))
print(list(filter(lambda x: x > 3, nums)))
print(reduce(lambda x, y: x*y, nums))

選択肢

A)

[2, 4, 6, 8, 10]
[4, 5]
120

B)

[1, 2, 3, 4, 5]
[3, 4, 5]
15

C)

[2, 4, 6, 8, 10]
[2, 3]
9

D)

エラーになる

Python3 エンジニア認定基礎試験 練習問題 Day27:組み込み関数(map, filter, reduce)

解答

A)
[2, 4, 6, 8, 10]
[4, 5]
120

■■■スポンサーリンク■■■

解説

print(list(map(lambda x: x*2, nums)))

各要素を2倍 → [2, 4, 6, 8, 10]

print(list(filter(lambda x: x > 3, nums)))

3より大きい要素 → [4, 5]

print(reduce(lambda x, y: x*y, nums))

1×2×3×4×5 = 120

👉 出力結果は

[2, 4, 6, 8, 10]
[4, 5]
120

👉 正解は A)
[2, 4, 6, 8, 10]
[4, 5]
120

✅ ポイント

  • map(func, list) → 各要素に関数を適用

  • filter(func, list) → 条件を満たす要素を抽出

  • reduce(func, list) → 累積処理で1つの値にまとめる

次回予告

Day28では 組み込み関数(any, all) を学びます。
ブール値の判定をまとめて処理できるようになりますよ!

参考

Python 3 エンジニア認定基礎試験 – Odyssey CBT
Python3 エンジニア認定基礎試験 出題範囲と学習プラン
Python3 エンジニア認定基礎試験 練習問題 Day1:変数の基本
Python3 エンジニア認定基礎試験 練習問題 Day2:変数の型(int型とstr型)
Python3 エンジニア認定基礎試験 練習問題 Day3:算術演算子と代入演算子
Python3 エンジニア認定基礎試験 練習問題 Day4:文字列の操作
Python3 エンジニア認定基礎試験 練習問題 Day5:比較演算子と論理演算子
Python3 エンジニア認定基礎試験 練習問題 Day6:if文(条件分岐)
Python3 エンジニア認定基礎試験 練習問題 Day7:ループ処理(for文・while文)
Python3 エンジニア認定基礎試験 練習問題 Day8:break文とcontinue文
Python3 エンジニア認定基礎試験 練習問題 Day9:リスト(list)の基本
Python3 エンジニア認定基礎試験 練習問題 Day10:リストの操作(append,remove,len など)
Python3 エンジニア認定基礎試験 練習問題 Day11:リストのスライス(部分取り出し)
Python3 エンジニア認定基礎試験 練習問題 Day12:タプル(tuple)の基本
Python3 エンジニア認定基礎試験 練習問題 Day13:辞書(dict)の基本
Python3 エンジニア認定基礎試験 練習問題 Day14:集合(set)の基本
Python3 エンジニア認定基礎試験 練習問題 Day15:関数の定義と呼び出し
Python3 エンジニア認定基礎試験 練習問題 Day16:関数のデフォルト引数とキーワード引数
Python3 エンジニア認定基礎試験 練習問題 Day17:可変長引数(*args, **kwargs)
Python3 エンジニア認定基礎試験 練習問題 Day18:関数のスコープ(ローカル変数とグローバル変数)
Python3 エンジニア認定基礎試験 練習問題 Day19:ネスト関数(関数の中の関数)
Python3 エンジニア認定基礎試験 練習問題 Day20:ラムダ式(無名関数)
Python3 エンジニア認定基礎試験 練習問題 Day21:組み込み関数(len, type, range など)
Python3 エンジニア認定基礎試験 練習問題 Day22:組み込み関数(sum,max,min,sorted)
Python3 エンジニア認定基礎試験 練習問題 Day23:文字列と組み込み関数(len,str,int,float)
Python3 エンジニア認定基礎試験 練習問題 Day24:組み込み関数(abs, round, pow)
Python3 エンジニア認定基礎試験 練習問題 Day25:組み込み関数(sorted の応用と key 引数)
Python3 エンジニア認定基礎試験 練習問題 Day26:組み込み関数(enumerate, zip)
Python3 エンジニア認定基礎試験 練習問題 Day27:組み込み関数(map, filter, reduce)
Python3 エンジニア認定基礎試験 練習問題 Day28:組み込み関数(any, all)

■■■スポンサーリンク■■■