简体   繁体   English

如何在使用地图功能时传递 kwargs?

[英]How to pass kwargs while using map function?

As above, I want to use map function to apply a function to a bunch of things and collect results in a list.如上所述,我想使用 map 函数将函数应用于一堆事物并将结果收集到列表中。 However, I don't see how can I pass kwargs to that function.但是,我不知道如何将 kwargs 传递给该函数。

For concreteness:对于具体性:

map(fun, elements)

What about kwargs?夸格呢?

Use a generator expression instead of a map .使用生成器表达式而不是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该问题已在Python `map` 和参数解包中得到解答

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从 Python 3 开始,标准映射可以单独列出多参数的参数

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.尽管命名变量的可变长度列表不太方便,尤其是在函数签名中存在**kwargs情况下。 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对于使用 lambda 的一行解决方案,请参阅Python `map` 和参数解包如果您不精通 lambda,可以按照以下步骤操作

def foldarg(param): 
    return f(param[0], **param[1])
list(map(foldarg, elements))

where elements is something like其中elements是这样的

[[[1,2], dict(x=3, y=4)],
[[-2,-2], dict(w=3, z=4)]]

For unnamed variables list you can also use itertools.starmap对于未命名的变量列表,您还可以使用 itertools.starmap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM