可以使用冪函數從該itertools recipe page:
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
https://stackoverflow.com/questions/374626/how-可以-I-發現,所有的-子集對的一集 - 與 - 這正是正元 – Ryan