是否有一种方法将Python元组扩展为函数-作为实际的参数?
例如,expand()在这里发挥了作用:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
我知道可以将myfun定义为myfun((a, b, c)),但当然可能存在遗留代码。
谢谢
这就是函数式编程方法。它将元组展开特性从语法糖中移除:
apply_tuple = lambda f, t: f(*t)
通过curry重新定义apply_tuple,在长期运行中节省大量部分调用:
from toolz import curry
apply_tuple = curry(apply_tuple)
使用示例:
from operator import add, eq
from toolz import thread_last
thread_last(
[(1,2), (3,4)],
(map, apply_tuple(add)),
list,
(eq, [3, 7])
)
# Prints 'True'
类似于@Dominykas的回答,这是一个将接受多参数函数转换为接受元函数的装饰器:
apply_tuple = lambda f: lambda args: f(*args)
示例1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
示例2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))