Python—;执行函数列表的所有排列
我希望执行函数列表的所有置换,包括部分置换和完整置换,并添加结果并将其放入列表中。 例如,假设我有三个功能:Python—;执行函数列表的所有排列,python,combinations,permutation,Python,Combinations,Permutation,我希望执行函数列表的所有置换,包括部分置换和完整置换,并添加结果并将其放入列表中。 例如,假设我有三个功能: foo(): return 1 bar(): return 2 bat(): return 3 我想执行foo(),bar(),bat(),foo()bar(),foo()bat()和foo()bar()bat() 因此,结果列表将是:[1,2,3,3,4,5,6] 知道我如何调用所有这些函数吗?实际上,我将有大约50个函数,并希望记录所有函数的所有组合 感谢您提供的帮助。您
foo():
return 1
bar():
return 2
bat():
return 3
我想执行foo()
,bar()
,bat()
,foo()bar()
,foo()bat()
和foo()bar()bat()
因此,结果列表将是:[1,2,3,3,4,5,6]
知道我如何调用所有这些函数吗?实际上,我将有大约50个函数,并希望记录所有函数的所有组合
感谢您提供的帮助。您知道可以在Python的列表中存储函数吗 您可以先定义所有函数:
def foo():
返回1
def bar():
返回2
def bat():
返回3
然后,创建一个列表以保存所有这些文件:
函数列表=[foo,bar,bat]
现在,您可以使用itertools.compositions执行您想要的操作:
来自itertools导入组合的
res_list=[]
对于范围内的i(len(函数列表)):
comb_list=list(组合(函数列表,i+1))
对于组合列表中的组合:
x=总和(e()表示组合中的e)
res_list.append(x)
打印(资源列表)
您知道可以在Python的列表中存储函数吗
您可以先定义所有函数:
def foo():
返回1
def bar():
返回2
def bat():
返回3
然后,创建一个列表以保存所有这些文件:
函数列表=[foo,bar,bat]
现在,您可以使用itertools.compositions执行您想要的操作:
来自itertools导入组合的
res_list=[]
对于范围内的i(len(函数列表)):
comb_list=list(组合(函数列表,i+1))
对于组合列表中的组合:
x=总和(e()表示组合中的e)
res_list.append(x)
打印(资源列表)
稍后编辑:
from itertools import chain, combinations
l = [foo, bar, bat]
[sum(j() for j in z) for z in chain.from_iterable(([y for y in x] for x in combinations(l, r)) for r in range(1,len(l)+1))]
稍后编辑:
from itertools import chain, combinations
l = [foo, bar, bat]
[sum(j() for j in z) for z in chain.from_iterable(([y for y in x] for x in combinations(l, r)) for r in range(1,len(l)+1))]
我假设您希望对每个计算出的和再次调用函数,也就是说,不要只计算函数结果一次,然后计算结果的和 在我看来,这是最干净的方法:
from itertools import combinations
def foo():
return 1
def bar():
return 2
def bat():
return 3
x = [foo, bar, bat]
# literally the list of sums of function results,
# for functions from all combinations of any length > 0 from x
result = [sum([f() for f in t]) for n in range(len(x)) for t in combinations(x, n+1)]
print(result)
输出:
[1, 2, 3, 3, 4, 5, 6]
我假设您希望对每个计算出的和再次调用函数,也就是说,不要只计算函数结果一次,然后计算结果的和 在我看来,这是最干净的方法:
from itertools import combinations
def foo():
return 1
def bar():
return 2
def bat():
return 3
x = [foo, bar, bat]
# literally the list of sums of function results,
# for functions from all combinations of any length > 0 from x
result = [sum([f() for f in t]) for n in range(len(x)) for t in combinations(x, n+1)]
print(result)
输出:
[1, 2, 3, 3, 4, 5, 6]
请注意,
foo()
、bar()
和bat()
的结果只计算一次-如果这些函数在每次调用时不总是返回相同的值,则这可能不是OP想要的结果。@Grismar感谢您的观察!走上了一条曾经被称为funcs的路,因为他说有50个funcs。。但是我明白了你的意思,并把它包含在了答案中。你的代码中还有一个错误,它只适用于长度为3的函数列表,因为你只要求使用r
oflen(l)-1
的组合。试着用4个或2个函数运行你的解决方案。另一个?哪一个是第一个?还注意到,正如您在列表理解中提到的,您的答案是“过于复杂的:)注意,foo()
、bar()
和bat()的结果
只计算一次-如果这些函数在每次调用时不总是返回相同的值,则这可能不是OP想要的结果。@Grismar感谢您的观察!走上了一条曾经被称为funcs的路,因为他说有50个funcs。。但是我明白了你的意思,并把它包含在了答案中。你的代码中还有一个错误,它只适用于长度为3的函数列表,因为你只要求使用r
oflen(l)-1
的组合。试着用4个或2个函数运行你的解决方案。另一个?哪一个是第一个?还注意到您的答案是您在列表中提到的“过于复杂”: