繁体   English   中英

如何在python中将许多功能进行所有组合?

[英]How to make all combinations of many functions in python?

所以我有

x = 3 

def first(x):
    return x+2

def second(x):
    return x/2

def third(x):
    return x*4

我想做一些类似的功能:

第一->第二->第三

但所有功能组合:如first-> second,first-> Third

并每次获取每种组合的x值。

而且我不仅需要乘以它们,还可以进行各种长度的多重组合。

这只是固定数量的组合: 如何在python中乘以函数?

问候和感谢

首先是组合部分:

>>> functions = [first, second, third]
>>> from itertools import combinations, permutations
>>> for n in range(len(functions)):
...     for comb in combinations(functions, n + 1):
...         for perm in permutations(comb, len(comb)):
...             print('_'.join(f.__name__ for f in perm))
...             
first
second
third
first_second
second_first
first_third
third_first
second_third
third_second
first_second_third
first_third_second
second_first_third
second_third_first
third_first_second
third_second_first

接下来的组成部分,从问题“ 如何在python中乘函数”中窃取@Composable装饰器 并使用它根据每个排列组合功能。

from operator import mul
from functools import reduce
for n in range(len(functions)):
    for comb in combinations(functions, n + 1):
        for perm in permutations(comb, len(comb)):
            func_name = '_'.join(f.__name__ for f in perm)
            func = reduce(mul, [Composable(f) for f in perm])
            d[func_name] = func

现在,您有了演示功能的命名空间(实际上是可调用的类):

>>> f = d['third_first_second']
>>> f(123)
254.0
>>> third(first(second(123)))
254.0
>>> ((123 / 2) + 2) * 4
254.0

暂无
暂无

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

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