下面是使用for循环和kwarg参数计算的test
方法的示例。
def test(first_arg='_', second_arg='_'):
return 'first_arg: %s\t second_arg: %s' % (first_arg, second_arg)
strings = ['a', 'b', 'c', 'd', 'e']
for s in strings:
print(test(second_arg=s))
如何使用地图功能实现相同的结果?
也就是说,如何将kwarg传递到map
函数?:
for i in map(test, strings):
print(i)
test
函数中参数的顺序不能更改,并且传递所有参数是不可接受的。也就是说,不需要以下地图等效解决方案:
# Passing two arguments is not a desired solution.
for s in strings:
print(test(first_arg='_', second_arg=s))
OR
# Editing the order of kwargs is also not possible.
def test(second_arg='_', first_arg='_'):
return 'first_arg: %s\t second_arg: %s' % (first_arg, second_arg)
for s in strings:
print(test(s))
答案 0 :(得分:0)
您可以使用lambda
创建一个新功能,使用test
唯一的参数second_arg=x
调用x
(){/ 1>}:
for i in map(lambda x: test(second_arg=x), strings):
print(i)
输出:
first_arg: _ second_arg: a
first_arg: _ second_arg: b
first_arg: _ second_arg: c
first_arg: _ second_arg: d
first_arg: _ second_arg: e
与此相同:
for s in strings:
print(test(second_arg=s))
输出:
first_arg: _ second_arg: a
first_arg: _ second_arg: b
first_arg: _ second_arg: c
first_arg: _ second_arg: d
first_arg: _ second_arg: e
或者,您可以定义辅助函数。这相当于上面lambda
的解决方案:
def call_with_second(x):
return test(second_arg=x)
for i in map(call_with_second, strings):
print(i)
输出:
first_arg: _ second_arg: a
first_arg: _ second_arg: b
first_arg: _ second_arg: c
first_arg: _ second_arg: d
first_arg: _ second_arg: e