我知道,
map(function, arguments)
相当于
for argument in arguments:
function(argument)
是否可以使用map功能执行以下操作?
for arg, kwargs in arguments:
function(arg, **kwargs)
答案 0 :(得分:19)
你可以使用lambda:
map(lambda a: function(a[0], **a[1]), arguments)
或者您可以使用生成器表达式或列表推导,具体取决于您的需要:
(function(a, **k) for a, k in arguments)
[function(a, **k) for a, k in arguments]
在Python 2中,map()
返回一个列表(因此列表推导是等价的),在Python 3中,map()
是一个生成器(因此生成器表达式可以替换它)。
没有直接执行此操作的内置或标准库方法;用例过于专业化。
答案 1 :(得分:11)
仅针对位置参数的情况,您可以使用itertools.starmap(fun, args)
:
返回一个迭代器,其值是从使用从给定序列中取得的参数元组计算的函数返回的。
示例:
from itertools import starmap
def f(i, arg):
print(arg * (i+1))
for _ in starmap(f, enumerate(["a", "b", "c"])):
pass
打印:
a
bb
ccc
答案 2 :(得分:0)
您必须记住,map会将参数作为一个元组而不是单独的参数传递给函数。如果您无法更改原始功能,可以使用辅助功能调用它:
def f(tup):
args, kwargs = tup
function(args, **kwargs)
map(f, arguments)
答案 3 :(得分:0)
我一直在满足同样的需求,最终制作了以下功能:
def kwarg_map(element_constructor, **kwarg_lists):
"""
A helper function for when you want to construct a chain of objects with individual arguments for each one. Can
be easier to read than a list expansion.
:param element_constructor: A function of the form object = fcn(**kwargs)
:param kwarg_lists: A dict of lists, where the index identifies two which element its corresponding value will go.
:return: A list of objects.
e.g. Initializing a chain of layers:
layer_sizes = [784, 240, 240, 10]
layers = kwarg_map(
Layer,
n_in = layer_sizes[:-1],
n_out = layer_sizes[1:],
activation = ['tanh', 'tanh', 'softmax'],
)
is equivalent to:
layers = [Layer(n_in=784, n_out=240, activation='tanh'), Layer(n_in=240, n_out=240, activation='tanh'), Layer(n_in=240, n_out=10, activation='softmax')]
"""
all_lens = [len(v) for v in kwarg_lists.values()]
assert len(kwarg_lists)>0, "You need to specify at least list of arguments (otherwise you don't need this function)"
n_elements = all_lens[0]
assert all(n_elements == le for le in all_lens), 'Inconsistent lengths: %s' % (all_lens, )
return [element_constructor(**{k: v[i] for k, v in kwarg_lists.iteritems()}) for i in xrange(n_elements)]