gpt4 book ai didi

python - 调用所有可能的函数组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:53:43 27 4
gpt4 key购买 nike

假设我有一堆函数,每个函数都标记为 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

关于python - 调用所有可能的函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com