如下所示,我有一个简单的循环打印4-8次。
我想让它在5个小时内随机打印4-8次.
import random
for i in range(random.randrange(4,8+1)):
print i+1
print "do other stuff here..."例如,它可以执行以下操作:
22:30: 1 do other stuff here...
22:41: 2 do other stuff here...
22:45: 3 do other stuff here...
23:50: 4 do other stuff here...
00:33: 5 do other stuff here...
01:23: 6 do other stuff here...
02:20: 7 do other stuff here...
03:10: 8 do other stuff here...由于它是随机的,它有可能做到:
13:34: 1 do other stuff here...
13:41: 2 do other stuff here...
13:45: 3 do other stuff here...
13:50: 4 do other stuff here...我怎么能做到这一点,我不知道如何使这两个循环一起运行。
威廉·丹曼
Sleeping for: 274 minutes
do other stuff here...
Sleeping for: 10 minutes
do other stuff here...
Sleeping for: 13 minutes
do other stuff here...
Sleeping for: 1 minutes
do other stuff here...
Sleeping for: 0 minutes
do other stuff here...
Sleeping for: 0 minutes
do other stuff here...
Sleeping for: 0 minutes
do other stuff here...
Sleeping for: 0 minutes
do other stuff here...对于tobias_k
total = 30
timer_list = sorted(random.randint(1, total) for i in range(random.randint(4, 8)))
timer_old = 0
timer_previous = 0
print timer_list
for counter, timer in enumerate(timer_list):
new_timer = timer_old - timer_previous
timer_previous = timer_old
sec = timedelta(seconds=int(new_timer))
d = datetime(1,1,1) + sec
if counter == 0:
print "First is instantatious"
else:
if d.hour and d.minute:
print "Sleeping for %d hour(s) %d minutes" % (d.hour, d.minute)
elif not d.hour and d.minute:
print "Sleeping for %d minutes and %d seconds" % (d.minute, d.second)
else:
print "Sleeping for %d seconds" % (d.second)
print "done"
time.sleep(timer - timer_old)
timer_old = timer发布于 2013-12-20 13:16:34
这里有另一个变体,基于Guntram的方法(以及我自己在问题下面的评论):
import random, time
total = 3600 * 5
times = sorted(random.randint(1, total) for i in range(random.randint(4, 8)))
last = 0
for t in times:
time.sleep(t - last)
last = t
print "Do something at %02d:%02d:%02d" % (t/3600, t/60%60, t%60)这将在5h间隔内创建4-8个时间点,并对它们进行排序。然后它会在第一段时间睡觉,做一些事情,为第一次和第二次的区别睡觉,再做一些事情,等等。
(可能的)优点是,间隔是相互独立的,应该在整个5h间隔内平均分配。在其他方法中,事件之间的间隔越来越小,因为它们是剩余时间的随机数量。
发布于 2013-12-20 12:49:54
获取4到8之间的随机数。创建一个包含这些元素的数组。为每个元素分配0到18000之间的随机值。对数组进行排序。循环遍历数组元素。在每个循环中,睡眠数组元素中的秒数减去先前循环中已经睡眠的秒数。打印“在这里做其他事情”。重复,直到循环结束。
发布于 2013-12-20 12:50:18
import time
import random
from time import gmtime, strftime
max_time_to_sleep = 18000
min_time_to_sleep = 120
for i in range(random.randrange(4,8+1)):
sleep_for = random.randrange(max_time_to_sleep)
while sleep_for < min_time_to_sleep:
if max_time_to_sleep <= min_time_to_sleep:
break
sleep_for = random.randrange(max_time_to_sleep)
if sleep_for == 0:
sleep_for = min_time_to_sleep
time.sleep(sleep_for)
max_time_to_sleep -= sleep_for
if max_time_to_sleep < min_time_to_sleep:
max_time_to_sleep = min_time_to_sleep
cur_time = strftime("%H:%M:%S", gmtime())
print "%s : do other stuff here..." % cur_timehttps://stackoverflow.com/questions/20703929
复制相似问题