简体   繁体   English

如何减慢Python中的循环?

[英]How can I slow down a loop in Python?

If I have a list l: 如果我有一个清单l:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Is there a way to control the following for loop so that the next element in the list is only printed one second after the previous? 有没有办法控制以下for循环,以便列表中的下一个元素仅在前一个后打印一秒?

for i in l:
    print i

In other words, is there a way to elegantly slow down a loop in Python? 换句话说,有没有办法优雅地减慢Python中的循环?

You can use time.sleep 你可以使用time.sleep

import time

for i in l:
    print i
    time.sleep(1)

If you use time.sleep(1) , your loops will run a little over a second since the looping and printing also takes some time. 如果你使用time.sleep(1) ,你的循环将运行一秒多一点,因为循环和打印也需要一些时间。 A better way is to sleep for the remainder of the second. 更好的方法是在第二秒的剩余时间内睡觉。 You can calculate that by using -time.time()%1 您可以使用-time.time()%1来计算它

>>> import time
>>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in L:
...     time.sleep(-time.time()%1)
...     print i
... 

It's easy to observe this by using print i, repr(time.time()) 通过使用print i, repr(time.time())很容易观察到这一点

>>> for i in L:
...     time.sleep(-time.time()%1)
...     print i, repr(time.time())
... 
0 1368580358.000628
1 1368580359.001082
2 1368580360.001083
3 1368580361.001095
4 1368580362.001149
5 1368580363.001085
6 1368580364.001089
7 1368580365.001086
8 1368580366.001086
9 1368580367.001085

vs VS

>>> for i in L:
...     time.sleep(1)
...     print i, repr(time.time())
... 
0 1368580334.104903
1 1368580335.106048
2 1368580336.106716
3 1368580337.107863
4 1368580338.109007
5 1368580339.110152
6 1368580340.111301
7 1368580341.112447
8 1368580342.113591
9 1368580343.114737

You can pause the code execution using time.sleep : 您可以使用time.sleep暂停代码执行:

import time

for i in l:
    print(i)
    time.sleep(1)

Use the time.sleep function. 使用time.sleep函数。 Just do time.sleep(1) in your function. 只需在你的函数中执行time.sleep(1)

Use time.sleep(number) : 使用time.sleep(number)

for i in range(i)
print(1)
time.sleep(0.05)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM