我有这个代码,我试图让它有60%的机会在时间小于12时选择3。 代码:
import random
from datetime import datetime
from random import choice
am = [1, 2, 3]
pm = [1, 2]
datetime.time(datetime.now())
c =(datetime.now().strftime('%H:%M:%S %p'))
if c < '12:00:00 PM':
ch = choice(am)
else:
ch = choice(pm)
if ch == 1:
print "hello"
if ch == 2:
print "how are you?"
if ch == 3:
print "good morning"
答案 0 :(得分:3)
如果您希望有60%的机会在列表am
中选择3,则可以编辑列表,以便60%的值为3。
am = [1, 2, 3, 3, 3]
答案 1 :(得分:0)
您可以使用weights
属性来设置某个成员被选中的机会。
例如:
import random
nums = [1, 2, 3]
result = random.choices(nums, weights=[20, 20, 60])
print (result)
如果您通过while
循环来运行它,如下所示:
import random
nums = [1, 2, 3]
while True:
#update Result value every loop run
result = random.choices(nums, weights=[20, 20, 60])
print (result)
该值将每次更新。编程愉快!