Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查循环中变量的值是否等于Python中的前一个值?_Python_Python 3.x_Loops_While Loop - Fatal编程技术网

如何检查循环中变量的值是否等于Python中的前一个值?

如何检查循环中变量的值是否等于Python中的前一个值?,python,python-3.x,loops,while-loop,Python,Python 3.x,Loops,While Loop,如果我有一个运行Python循环的函数: 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) 如何检查时间是否与上次相同,并中断循环,或者在这种情况下

如果我有一个运行Python循环的函数:

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)
如何检查时间是否与上次相同,并中断循环,或者在这种情况下使函数不执行任何操作

我的想法是:

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

但是如果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)

听起来您需要第二个变量来存储time_previous,或者让time变量存储一个元组,其中一个是当前元组,另一个是前一元组。需要将以前的时间存储在某个地方以便进行比较。不要命名可变时间,因为它会遮挡内置时间;time.sleep1将失败。@Mike我已经编辑了这个问题,以显示我的想法,但由于我给出的原因,我认为它行不通。我觉得很难理解怎么做。如果您能编写代码让我实现这一点,我将不胜感激:您的想法会奏效,但If语句需要在设置新时间的行之后,在设置上一个时间的行之前=time@Stuart这是有道理的!谢谢你,斯图尔特。