调用所有可能的函数组合
Calling every possible combination of functions
假设我有一堆函数,每个函数都标记为 doThing1、doThing2 等,直到 doThing10。我想调用这些函数的所有可能组合。不必调用每个函数,但是每个函数只能调用一次。我怎样才能在 python 中以有效的方式实现它?
使用 itertools.permutations(iterable\[, r\])
获取所有排列并将您的函数放入列表中。
这是一个例子:
import itertools
def doThing1():
print "thing 1"
def doThing2():
print "thing 2"
def doThing3():
print "thing 3"
functions = [doThing1, doThing2, doThing3]
for func_list in itertools.permutations(functions):
for func in func_list:
func()
这是它的输出:
$ python permutations.py
thing 1
thing 2
thing 3
thing 1
thing 3
thing 2
thing 2
thing 1
thing 3
thing 2
thing 3
thing 1
thing 3
thing 1
thing 2
thing 3
thing 2
thing 1
假设我有一堆函数,每个函数都标记为 doThing1、doThing2 等,直到 doThing10。我想调用这些函数的所有可能组合。不必调用每个函数,但是每个函数只能调用一次。我怎样才能在 python 中以有效的方式实现它?
使用 itertools.permutations(iterable\[, r\])
获取所有排列并将您的函数放入列表中。
这是一个例子:
import itertools
def doThing1():
print "thing 1"
def doThing2():
print "thing 2"
def doThing3():
print "thing 3"
functions = [doThing1, doThing2, doThing3]
for func_list in itertools.permutations(functions):
for func in func_list:
func()
这是它的输出:
$ python permutations.py
thing 1
thing 2
thing 3
thing 1
thing 3
thing 2
thing 2
thing 1
thing 3
thing 2
thing 3
thing 1
thing 3
thing 1
thing 2
thing 3
thing 2
thing 1