map関数【builtin】
説明:イテラブルオブジェクトから取り出した値を指定した関数に渡した結果をイテラブルなオブジェクトとして得るための関数である。指定する関数には、ユーザ関数(def文で定義したもの、ラムダ式)ライブラリ関数、ビルトイン関数などが利用できる。
書式:
(戻り値) = map( 関数、イテラブルオブジェクト)
戻り値:map型オブジェクト
基本的な使い方
abs関数【builtin】に適用した例。
code:map1.py
input = 1, -2, 3, -4
output = map(abs, input)
# 結果の確認
print(output)
for i in output:
print(i)
結果はイテラブルオブジェクトなのでrangeオブジェクトのようにfor文で取り出す必要がある
引数を2つ要求する関数powを用いた例。
code:map2.py
input1 = 1, 2, 3, 4
input2 = 2, 2, 2, 2
output = map(pow, input1, input2)
print(output)
for i in output:
print(i)
def文で定義したユーザ関数にも適用することができる。
code:map3.py
def my_mean(x, y, z):
return (x + y + z)/3
input1 = 1,2,3,4
input2 = 2,2,2,2
input3 = 0,2,1,3
output = map(my_mean, input1, input2, input3)
for i in output:
print(i)
戻り値が2つある関数の場合はどうなるか?
code:map4.py
def my_mean(x, y):
return x*2, y/2
data1 = 1,2,3,4
data2 = 2,2,2,2
result = map(my_mean, data1, data2)
for i in result:
print(i)
結果はタプルで返された。これをアンパックするなどして移行の処理に活用します。
ラムダ式に用いる
ラムダ式を用いた例、引数は1つ
code:map5.py
data = 1, 2, 3, 4
result = map(lambda x:x*2, data)
for i in result:
print(i)
ラムダ式に複数のデータを与えてみる
code:map6.py
input1 = 1, 2, 3, 4
input2 = 2, 2, 2, 2
input3 = 0, 2, 1, 3
output = map(lambda x, y, z: (x + y + z)/3, input1, input2, input3)
for i in output:
print(i)
まさに記述した通りに動作するという印象である。