[英]How can repeat 10 times randomly in several available functions in python?
對於幾個功能:ftn_1,ftn_2,...,ftnk我想在上面隨機重復10次。 (整個時間是k ^ 10。)
我發現一些函數的行為類似於這種方式,但它似乎僅對字符串起作用:itertools.product
def ftn1():
...
def ftn2():
...
x=0;
itertools.product(x=ftn1(x), x=ftn2(x), .., x=ftnk(x), [repeat=10])
我想做類似上面的事情,並在所有情況下找到最小值。
您只需要創建所有函數的列表(或元組),然后在其上使用random即可,例如:
import random
funcs = [ftn1, ftn2, ftn3, ..., ftnN]
my_func = random.choice(funcs)
然后,您可以使用任意選擇的參數調用my_func
。
如果您的意思是您有k
函數,並且希望總共調用10
次,但是以隨機順序,您可以shuffle()
列出它們。
為了理智起見,此示例具有3個功能,並調用了2次。 也為所有這些參數提供了一個參數,它被寫成:
import random
def f1(x):
print("f1:"+str(x))
def f2(x):
print("f2:"+str(x))
def f3(x):
print("f3:"+str(x))
# here you could have more functions...
repeats=[f1,f2,f3]*2 # ... and they could be listed here, and 2 could be 10
print("Default order:")
for i in range(len(repeats)):
repeats[i](i) # repeats[i] is a function here, which is invoked with i
random.shuffle(repeats)
print("Shuffled order:")
for i in range(len(repeats)):
repeats[i](i)
輸出示例(當然,由於隨機性而有所不同)
Default order: f1:0 f2:1 f3:2 f1:3 f2:4 f3:5 Shuffled order: f3:0 f1:1 f1:2 f2:3 f2:4 f3:5
盡管它們的數量不是3 ^ 2,而是3 * 2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.