Python中Clojure样式的函数“threading”

2024-04-25 05:59:11 发布

您现在位置:Python中文网/ 问答频道 /正文

Clojure有一个“->;”宏,它递归地插入每个表达式作为下一个表达式的第一个参数。在

这意味着我可以写:

(-> arg f1 f2 f3)

它的行为类似于(外壳管道):

^{pr2}$

我想用Python来做这个;但是,搜索似乎是一场噩梦!我无法搜索“->;”,也无法搜索Python函数线程!在

有没有一种方法可以重载|运算符,这样我就可以用Python编写它了?在

arg | f1 | f2 | f3

谢谢!在


Tags: 方法函数gt参数管道表达式arg外壳
3条回答

或者可以按以下方式使用reduce函数:

reduce(lambda x,f : f(x), [f1,f2,f3], arg)

或者尝试https://mdk.fr/blog/pipe-infix-syntax-for-python.html 提供如下语法的模块:

  fib() | take_while(lambda x: x < 1000000)
        | where(lambda x: x % 2)
        | select(lambda x: x * x)
        | sum()

你自己可以很容易地实现这样的东西。在

def compose(current_value, *args):
    for func in args:
        current_value = func(current_value)
    return current_value

def double(n):
    return 2*n

print compose(5, double, double) # prints 20

相关问题 更多 >