[英]How to check if the value of a variable in a loop is equal to the previous value in Python?
如果我有一个运行 Python 循环的 function :
def read_progress():
while True:
with open('progress.txt', 'r') as f:
lines = f.readlines()
time = lines[-5].split('=')[-1].split('.')[0]
time.sleep(1)
如果是这种情况,我如何检查time
是否与上次相同并跳出循环(或使 function 什么都不做)?
我在想类似的事情:
def read_progress():
previous_time = '00:00:00'
while True:
if previous_time == time:
break
with open('progress.txt', 'r') as f:
lines = f.readlines()
time = lines[-5].split('=')[-1].split('.')[0]
time.sleep(1)
previous_time = time
但是if previous_time == time
不会因为我让previous_time
等于time
而总是正确的吗? 我会发现这样的事情很难理解,所以如果有人可以编辑错误的代码,我将不胜感激,这样我就可以实现我想要的:)
正如@Stuart 更正的那样,需要移动 if 语句。 这是解决方案:
def read_progress():
previous_time = '00:00:00'
while True:
with open('progress.txt', 'r') as f:
lines = f.readlines()
current_time = lines[-5].split('=')[-1].split('.')[0]
if previous_time == current_time:
break
previous_time = current_time
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.