map関数
イテラブルなオブジェクトから取り出した値に対して関数を適用し、結果をイテラブルなオブジェクトで返すもの。
適用する関数には、ユーザ関数(def文で定義したもの、ラムダ式)ライブラリ関数、ビルトイン関数などが利用できる。
ビルトイン関数のabsを用いた例
code:python
input = 1, -2, 3, -4
output = map(abs, input)
# 結果の確認
print(output)
## 結果はrangeオブジェクトのようにfor文で取り出す必要がある
for i in output:
print(i)
引数を2つ要求するビルトイン関数powを用いた例
code:python
input1 = 1, 2, 3, 4
input2 = 2, 2, 2, 2
output = map(pow, input1, input)
print(output)
for i in output:
print(i)
def文で定義した関数を用いた例
code:python
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:python
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:python
data = 1, 2, 3, 4
result = map(lambda x:x*2, data)
for i in result:
print(i)
ラムダ式に複数のデータを与えてみる
code:python
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)
まさに記述した通りに動作するという印象である。