Python检查变量是否高于上一个循环

时间:2018-08-23 11:32:00

标签: python

刚开始使用Python,我正在编写一个检查警报的程序,基本上,我需要它来跟踪一个数字,如果下一个循环中该数字更高,则可以进行处理。

def code():
yellowCount = 0
orangeCount = 0
redCount = 0
blueCount = 0

print ("----------------------------------------")
print ("Running check on ")
# do your stuff
for line in open(txtFiles[0]):
    if 'details_YELLOW' in line:
        yellowCount = yellowCount + 1
    elif 'details_ORANGE' in line:
        orangeCount = orangeCount + 1
    elif 'details_RED' in line:
        redCount = redCount + 1
        toaster.show_toast("xxxxx","Red alert detected on ")

    elif 'details_BLUE' in line:
        blueCount = blueCount + 1
print (str(yellowCount) + " Yellow alerts")
print (str(orangeCount) + " Orange alerts")
print (str(redCount) + " Red alerts")
print (str(blueCount) + " Blue alerts")

有一段代码摘录,最好的方法是什么?全局变量?基本上,我只想在有新警报时发出警报,而不是在每次代码运行时都针对检测到的每个警报发出警报。

代码输出示例

==================
Downloading Alerts
==================
----------------------------------------
Running check on 
0 Yellow alerts
0 Orange alerts
0 Red alerts
0 Blue alerts
----------------------------------------
Running check on 
0 Yellow alerts
1 Orange alerts
0 Red alerts
0 Blue alerts

因此,我只想在橙色警报在第二秒变为2时执行代码

2 个答案:

答案 0 :(得分:0)

这很容易做到,所有您需要做的就是将变量保留在for循环之外,该变量将跟踪先前的值:

prev_count = 0
for ... :
    count = ...
    if prev_count < count:
        #do stuff
    prev_count = count

答案 1 :(得分:0)

很明显,整数值不记得它的历史记录,因此您可以通过各种变通方法来做到这一点:

  • 保留标记yellow_changed = False。如果满足条件,则将其更改为True。但是,您必须在每次迭代开始时将它们重置为False
  • 直接进行操作:

    if 'details_YELLOW' in line:
       # yellowCount = yellowCount + 1
       do_the_yellow_stuff()
    
  • 保留值列表。每次迭代yellow_values.append(yellowCount),然后检查是否yellowCount[-1] > yellowCount[-2]