15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

map関数の返り値

Last updated at Posted at 2017-10-30

同じ内容は溢れてるけど、自分がハマったのでメモ。

map関数

なにかしらの関数にリストの全要素を読ませるための高階関数。
無名関数(lambda)の場合はこんな感じ。

map(lambda x: x + 2, [1,2,3,4])

defにするなら

def add(x):
    return x + 2

map(add, [1,2,3,4])

返り値

で、問題はこのmapの戻り値。mapはリストに対して関数を実行した値を返すわけではなく、イテレータを返す。リストを返すわけではない。

つまり

print(map(lambda x: x + 2, [1,2,3,4])

とするとイテレータを含むmapオブジェクトが返ってくる。
そのまま扱うにはいいが、例えば

output = map(lambda x: x+2, [1,2,3,4])
print(np.array(output) * 2)

こんな感じで計算をかけるとTypeErrorを吐かれる。
というわけでmapをかけたあとに計算に持ち込むにはlist化しておく。

output = list(map(lambda x: x+2, [1,2,3,4]))
print(np.array(output) * 2)

これでめでたく返りは

[6, 8, 10, 12]

となりました。

引き渡し

interp2dを使うためにリストをxとyを自作関数に投げる場合。

x = [1,2,3,4]
y = [7,8,9,10]
xnew, ynew = np.meshgrid(x, y)

def func(x, y):
    return f(x, y)

z = list(map(func, xnew, ynew))
inter = interpolate.interp2d(x, y, z, kind='cubic')

とするわけだが、funcの内容によっては問題が発生する(した)。
この場合、mapがfuncに渡すのはxnew[0]である[1,2,3,4]のリストを渡す。
ちゃんとfuncが考えられていればいいが、たまにリストで渡されるとエラーする関数が生まれる。(例えば、受け取った引数をそのままtxtに吐き出して別exeに引き渡す時とか)

そういう時はravelでバラして引き渡すとうまくいく。

x = [1,2,3,4]
y = [7,8,9,10]
xnew, ynew = np.meshgrid(x, y)

def func(x, y):
    return f(x, y)

z = list(map(func, xnew.ravel(), ynew.ravel()))

参考

https://qiita.com/croissant1028/items/94c4b7fd360cfcdef0e4
https://qiita.com/hitoshi_xyz/items/ec82e108c3ec827512a3

それぞれもっとうまい書き方あるだろうなあ。

15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?