As above, I want to use map function to apply a function to a bunch of things and collect results in a list. However, I don't see how can I pass kwargs to that function.
For concreteness:
map(fun, elements)
What about kwargs?
Use a generator expression instead of a map
.
(fun(x, **kwargs) for x in elements)
eg
reduce(fun(x, **kwargs) for x in elements)
Or if you're going straight to a list, use alist comprehension instead:
[fun(x, **kwargs) for x in elements]
The question is already answered at Python `map` and arguments unpacking
The map does not exactly support named variable, though can handle multiple variable based on position.
Since Python 3 the standard map can list arguments of multi-argument separately
map(fun, listx, listy, listz)
It is though less convenient for variable length list of named variables, especially in presence of **kwargs
in the function signature. You can, though, introduce some intermediate function to pack separately positional and named arguments. For one line solution with lambda see Python `map` and arguments unpacking If you are not proficient with lambda, you can go as below
def foldarg(param):
return f(param[0], **param[1])
list(map(foldarg, elements))
where elements
is something like
[[[1,2], dict(x=3, y=4)],
[[-2,-2], dict(w=3, z=4)]]
For unnamed variables list you can also use itertools.starmap
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.