在使用地图功能评估函数时如何使用kwarg参数

时间:2017-01-05 15:06:35

标签: python python-3.x functional-programming itertools functools

下面是使用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))

1 个答案:

答案 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