相当于 Python 中 R 的 `do.call`

Dee*_*ena 7 python r python-2.7

do.callpython中是否有相当于R的?

do.call(what = 'sum', args = list(1:10)) #[1] 55
do.call(what = 'mean', args = list(1:10)) #[1] 5.5

?do.call
# Description
# do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

没有内置的,但很容易构造一个等效的。

您可以使用__builtin__(Python 2) 或builtins(Python 3) 模块从内置命名空间中查找任何对象,然后将任意参数应用到 with*args**kwargs语法:

try:
    # Python 2
    import __builtin__ as builtins
except ImportError:
    # Python 3
    import builtins

def do_call(what, *args, **kwargs):
    return getattr(builtins, what)(*args, **kwargs)

do_call('sum', range(1, 11))
Run Code Online (Sandbox Code Playgroud)

一般来说,我们不会在 Python 中这样做。如果必须将字符串翻译成函数对象,通常最好构建自定义字典:

functions = {
    'sum': sum,
    'mean': lambda v: sum(v) / len(v),
}
Run Code Online (Sandbox Code Playgroud)

然后从该字典中查找函数:

functions['sum'](range(1, 11))
Run Code Online (Sandbox Code Playgroud)

这让您可以严格控制哪些名称可用于动态代码,防止用户通过调用内置函数的破坏性或破坏性效果来打扰自己。


Kon*_*lph 5

do.call几乎相当于Python中的splat 运算符

def mysum(a, b, c):
    return sum([a, b, c])

# normal call:
mysum(1, 2, 3)

# with a list of arguments:
mysum(*[1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

请注意,我必须定义自己的sum函数,因为 Pythonsum已经将 alist作为参数,因此您的原始代码就是

sum(range(1, 11))
Run Code Online (Sandbox Code Playgroud)

R 有另一个特点:在do.call内部对其第一个参数执行函数查找。这意味着即使它是字符串而不是实际函数,它也会找到该函数。上面的 Python 等价物没有这样做 - 请参阅 Martijn's answer 以获取解决方案。