LoginSignup
30
22

More than 5 years have passed since last update.

python の map オブジェクトを list にした後は何も残らない

Posted at

map/zip/filter オブジェクトに対して、list を2回やると空っぽになります。

list_twice
>>> xs = [1, 2, 3]
>>> mapped = map(lambda x:x+1, xs)
>>> list(mapped)
[2, 3, 4]
>>> list(mapped)
[]

最初何が起こったのかわからずバグじゃないかとか、破壊的メソッドか!?などと思ったりしたわけですが、仕様らしいです。http://stackoverflow.com/questions/19759247/listing-a-filter-object-twice-will-return-a-blank-list

なので適当に書いてはいけない

もともとは以下のように dict を作ったところでハマりました。

bad_code
xs = map(func, my_list)
ys = dict(zip([x.key for x in xs], xs))

今読み返すと悲しいコードですが・・・ list() を使わなくても内包表記だろうがなんだろうが iterate すると消えてしまうので、この場合 zip の2番めの xs は空っぽになってしまったのでした。なので、map した場合は注意するように頑張ることにしました。

ちなみに上のコードは、以下のようにして解決しました。

bad_code
xs = map(func, my_list)
ys = {x.key:x for x in xs}

おかげで Python3 では、内包表記が dict と set に対応してるというのを学びました。

30
22
3

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
30
22