我有一段代码(由stackoverflow中的某人编写)根据时间变量分隔条件:
factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}
wantedTime = 19;
String_1={}
String_2={}
total = 0
for k,v in factors.items():## or factors.iteritems()
time = int(v.split(" ")[0])
if total+time <= wantedTime:
total +=time
String_1[k]=v
else:
String_2[k]=v
但是,似乎总是为第一个字符串选择相同的变量。例如,如果我运行此脚本5次,我想要19分钟的变量,它总是以相同的方式分割它们。我想要的是随机化:
因此有时会选择因子4,有时会选择因子1和3。
提前谢谢
答案 0 :(得分:3)
我认为你可以随意改变迭代:
import random
for k, v in sorted(factors.items(), key=lambda k: random.random()):
答案 1 :(得分:1)
为了它而将我的评论转换为答案。
from random import randint
factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}
wantedTime = 19;
String_1={}
String_2={}
total = 0
for k in list(factors.keys())[randint(0, 1000)%len(factors)-1]:
v = factors[k]
time = int(v.split(" ")[0])
if total+time <= wantedTime:
total +=time
String_1[k]=v
else:
String_2[k]=v