For the map / zip / filter object, do list twice and it will be empty.
list_twice
>>> xs = [1, 2, 3]
>>> mapped = map(lambda x:x+1, xs)
>>> list(mapped)
[2, 3, 4]
>>> list(mapped)
[]
I don't know what happened at first, it's a bug, or it's a destructive method! ?? I thought, but it seems to be a specification. http://stackoverflow.com/questions/19759247/listing-a-filter-object-twice-will-return-a-blank-list
Originally, I was addicted to making a dict as follows.
bad_code
xs = map(func, my_list)
ys = dict(zip([x.key for x in xs], xs))
It's a sad code to read back now ... It doesn't matter if it's included or not without using list (), it disappears when iterate, so in this case the second xs of the zip is empty. It was. So I decided to do my best to be careful when mapping.
By the way, the above code was solved as follows.
bad_code
xs = map(func, my_list)
ys = {x.key:x for x in xs}
Thanks to that, I learned that in Python3, comprehensions correspond to dict and set.
Recommended Posts