python我应该用什么代替

时间:2019-03-04 22:19:52

标签: python while-loop

不建议使用while循环,因为它不是pythonic。我已经进行了一些研究,并且我了解大多数情况。如果有人可以帮助我,我很难想出其他替代方法。

time = getTime()
while time > dt:
    doSth(dt)
    time -= dt

您如何将其更改为更Python化的方式?

for i in range(time//dt):
    doSth(dt)

怎么样?

1 个答案:

答案 0 :(得分:0)

您可以在for循环中遍历如下所示的范围对象,尽管您的while循环并没有Python般的含义:

for time in range(getTime(), 0, -dt):
    doSth(dt) # or perhaps your mean to call doSth(time), since dt does not change

或者,如果您的时间戳记是一个浮点数:

for i in range(getTime() // dt):
    doSth(getTime() - i * dt)
相关问题