擅长:python、mysql、java
<p>可以使用<a href="https://docs.python.org/3/library/itertools.html#recipes" rel="nofollow noreferrer">itertools recipe page</a>中的powerset函数:</p>
<pre><code>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
</code></pre>
<p>它产生以下输出:</p>
<pre><code>f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3
</code></pre>