簡體   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