Below is an example of a test
method which is evaluated using a for loop and a kwarg argument.
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))
How can the same result be achieved using map functionality?
That is, how can a kwarg be passed into the map
function?:
for i in map(test, strings):
print(i)
The order of the arguments in the test
function cannot be changed and passing all arguments is not acceptable. That is, the below map-equivalent solutions are not desired:
# 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))
You can use
lambda
to create a new function that callstest
() withsecond_arg=x
using its only argumentx
:the output:
is the same as for this:
Output:
Alternatively, you can define a helper function. This is equivalent to the solutions with
lambda
above:Output: