簡體   English   中英

通過python中的多個if語句迭代列表

[英]iterating list through multiple if statement in python

我有一個列表和兩個要比較的值:

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。

此代碼打印 OK,但應打印 CRITICAL。

您正在每次迭代替換status的值,因此您實際上只是檢查列表中的最后一個元素,並且它低於w因此它打印OK

鑒於您的方法,一種明顯的修復方法是一旦一個值很關鍵就中斷for循環,並且一旦一個元素觸發警告,就不要檢查 OK 。

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'

以下情況如何:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM