通过python中的多个if语句迭代列表

时间:2016-04-04 14:55:05

标签: python list loops if-statement

我有一个列表和两个要比较的值:

mylist = [98, 10, 12]
w = 85
c = 90

for i in mylist:
    if i <= w:
        status = "OK"
    elif i >= w and i < c:
        status = "WARNING"
    elif i >= c:
        status = "CRITICAL"

print status

条件是: a)如果列表中的所有元素都小于w和c,则应打印OK。 b)如果任何元素大于w且小于c,则应打印WARNING。 c)如果任何元素大于c,则应打印CRITICAL。

此代码打印正常,但应打印CRITICAL。

2 个答案:

答案 0 :(得分:1)

您正在替换每次迭代status的值,因此您只需检查列表中的最后一个元素,然后在w下面,以便打印OK

鉴于你的方法,一种明显的修复方法就是在一个值很关键时立即中断for - 循环,并且只要一个元素已经触发警告就不会检查确定。

mylist = [98, 10, 12]
w = 85
c = 90
status = 'OK' # assume it's ok until you found a value exceeding the threshold
for i in mylist:
    if status == 'OK' and i < w: # Only check OK as long as the status is ok
        status = "OK"
    elif i >= w and i < c:
        status = "WARNING"
    elif i >= c:
        status = "CRITICAL"
        break # End the loop as soon as a value triggered critical

print status

除了提案之外,我建议只找到max值并进行比较:

maximum = max(mylist)
if maximum < w:
    status = 'OK'
elif maximum < c:
    status = 'WARNING'
else:
    status = 'CRITICAL'

答案 1 :(得分:0)

以下内容如何:

def check(mylist):
    w, c = 0.85, 0.90
    if any(x >= c for x in mylist):
        # there is an element larger than c
        return "CRITICAL"
    elif any(x >= w for x in mylist): 
        # there is an element larger than w
        return "WARNING"
    else:
        return "OK"

然后:

>>> check([98, 10, 12])
'CRITICAL'