简体   繁体   中英

Map equivalent for list comprehension

[foo(item['fieldA'], item['fieldC']) for item in barlist]

Is there a map equivalent for this?

I mean, something like this:

map(foo, [(item['fieldA'], item['fieldB']) for item in barlist])

but it doesn't work. Just curious.

You are looking for itertools.starmap() :

from itertools import starmap

starmap(foo, ((item['fieldA'], item['fieldB']) for item in barlist))

starmap applies each item from the iterable as separate arguments to the callable. The nested generator expression could be replaced with an operator.itemgetter() object for more mapping goodness:

from itertools import starmap
from operator import itemgetter

starmap(foo, map(itemgetter('fieldA', 'fieldB'), barlist))

Like all callables in itertools , this produces an iterator, not a list. But if you were using Python 3, so does map() , anyway. If you are using Python 2, it may be an idea to swap out map() for itertools.imap() here.

Nothing beats itertools.starmap , like Martijn explained. But if you like to use only map , then you can simulate what starmap internally does, like this

map(lambda fields: foo(*fields), ((it['fieldA'], it['fieldC']) for it in bars))

Or you can use operator.itemgetter , like this

map(lambda fields: foo(*fields),(itemgetter("fieldA","fieldC") for item in bars))

*fields is nothing but unpacking the values which we received with itemgetter("fieldA","fieldC") . So, the value of fieldA will be the first argument to foo and the value of fieldC will be the second argument to foo .

Something like this.

bar = lambda x: foo(x['fieldA'], x['fieldC'])
map(bar, barlist)

Still, it is rather inadvisable to use map, not list comprehension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM