Python 在各种可能的组合中调用函数
我有一个函数列表。我想调用这些函数的每个可能组合,其中每个函数要么调用一次,要么根本不调用。他们的顺序不重要 例如:Python 在各种可能的组合中调用函数,python,algorithm,computer-science,combinatorics,Python,Algorithm,Computer Science,Combinatorics,我有一个函数列表。我想调用这些函数的每个可能组合,其中每个函数要么调用一次,要么根本不调用。他们的顺序不重要 例如: functionList = [function1, function2, function3] 我想单独调用function1()、function1()+function2()、function1()+function2()+function3()以及function2()等等 我将如何在python中实现这一点?我想用itertools.combines,但似乎我不能用它
functionList = [function1, function2, function3]
我想单独调用function1()、function1()+function2()、function1()+function2()+function3()以及function2()等等
我将如何在python中实现这一点?我想用itertools.combines,但似乎我不能用它来解决我的问题。itertools很好用。但是你需要通过你想要使用的数字…在1和你的集合中的数字之间。不确定是否需要0作为退化情况。下面的工作。它可以被压缩,但它的可读性很好。查找“python函数指针”
您可以从以下位置使用powerset功能: 它产生以下输出:
f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3
from itertools import chain, combinations
def powerset(iterable):
"""
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
"""
xs = list(iterable)
# note we return an iterator rather than a list
return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))
def f1():
return "f1"
def f2():
return "f2"
def f3():
return "f3"
functions = [f1, f2, f3]
for function_comb in powerset(functions):
out = ""
if not function_comb:
continue # skip the empty set of functions
for f in function_comb:
out += f()
print out
f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3