Skip to main content
 首页 » 编程设计

python之函数组合、元组和拆包

2024年10月01日7sky-heaven

(声明:不是 Python 小子,所以请保持温柔)

我正在尝试使用以下方法编写函数:

def compose(*functions): 
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x) 

对于标量 函数,它按预期工作。我喜欢使用返回元组的函数和其他接受多个参数的函数,例如。

def dummy(name): 
  return (name, len(name), name.upper()) 
 
def transform(name, size, upper): 
  return (upper, -size, name) 
 
# What I want to achieve using composition,  
# ie. f = compose(transform, dummy) 
transform(*dummy('Australia')) 
=> ('AUSTRALIA', -9, 'Australia') 

由于 dummy 返回一个元组,而 transform 接受三个参数,因此我需要解压该值。

如何使用上面的 compose 函数实现此目的?如果我这样尝试,我会得到:

f = compose(transform, dummy) 
f('Australia') 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "<stdin>", line 2, in <lambda> 
  File "<stdin>", line 2, in <lambda> 
TypeError: transform() takes exactly 3 arguments (1 given) 

有没有办法改变 compose 使其在需要的地方解包?

请您参考如下方法:

Bruno 提供的答案中的 compose 函数确实为具有多个参数的函数完成了工作,但不幸的是,它不再适用于标量函数。

利用 Python 将元组“解包”为位置参数这一事实,这就是我解决它的方法:

import functools 
 
def compose(*functions): 
  def pack(x): return x if type(x) is tuple else (x,) 
 
  return functools.reduce( 
    lambda acc, f: lambda *y: f(*pack(acc(*pack(y)))), reversed(functions), lambda *x: x) 

现在可以正常工作了,例如。

######################### 
# scalar-valued functions 
######################### 
 
def a(x): return x + 1 
def b(x): return -x 
 
# explicit 
> a(b(b(a(15)))) 
# => 17 
 
# compose 
> compose(a, b, b, a)(15) 
=> 17 
 
 
######################## 
# tuple-valued functions 
######################## 
 
def dummy(x): 
  return (x.upper(), len(x), x) 
def trans(a, b, c): 
  return (b, c, a) 
 
# explicit 
> trans(*dummy('Australia')) 
# => ('AUSTRALIA', 9, 'Australia') 
 
# compose 
> compose(trans, dummy)('Australia') 
# => ('AUSTRALIA', 9, 'Australia') 

这也适用于多个参数:

def add(x, y): return x + y 
 
# explicit 
> b(a(add(5, 3))) 
=> -9 
 
# compose 
> compose(b, a, add)(5, 3) 
=> -9