Hee*_*ryu 2 python list-comprehension iterable-unpacking map-function
[foo(item['fieldA'], item['fieldC']) for item in barlist]
Run Code Online (Sandbox Code Playgroud)
有没有相同的地图?
我的意思是,像这样:
map(foo, [(item['fieldA'], item['fieldB']) for item in barlist])
Run Code Online (Sandbox Code Playgroud)
但它不起作用.只是好奇.
您正在寻找itertools.starmap()
:
from itertools import starmap
starmap(foo, ((item['fieldA'], item['fieldB']) for item in barlist))
Run Code Online (Sandbox Code Playgroud)
starmap
将iterable中的每个项作为单独的参数应用于callable.嵌套的生成器表达式可以替换为operator.itemgetter()
对象以获得更多映射优势:
from itertools import starmap
from operator import itemgetter
starmap(foo, map(itemgetter('fieldA', 'fieldB'), barlist))
Run Code Online (Sandbox Code Playgroud)
像所有的callables一样itertools
,这会产生一个迭代器,而不是一个列表.但是,如果您使用的是Python 3,那么map()
无论如何都是如此.如果您正在使用Python 2中,它可能是一个想法,换出map()
了itertools.imap()
这里.