【问题标题】:iterating list through multiple if statement in python通过python中的多个if语句迭代列表
【发布时间】:2016-07-24 04:43:21
【问题描述】:

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

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。

【问题讨论】:

  • 无法复制,打印了两个OKs和三个CRITICALs。
  • 要么您没有向我们展示实际代码,要么您对“停止”有了一个新的有趣的定义。
  • 在实际循环中是否可能有breakreturn?两者都会阻止循环继续。
  • 那么你想让程序打印“Ok”、“Warning”和“Critical”吗?打印“警告”的行也永远不会运行。
  • 如果不清楚预期结果是什么,就很难“纠正代码”。这显然会打印“OK”、“OK”、“CRITICAL”、“CRITICAL”、“CRITICAL”。这不是预期的结果吗?

标签: python list loops if-statement


【解决方案1】:

以下内容如何:

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'

【讨论】:

    【解决方案2】:

    您将在每次迭代中替换 status 的值,因此您实际上只需检查列表中的最后一个元素,该元素位于 w 下方,因此它会打印 OK

    鉴于您的方法,一种明显的解决方法是在一个值至关重要时立即中断for-loop,并且一旦一个元素已经触发了警告,就不要检查 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'
    

    【讨论】:

    • 使用max 的建议确实是这个问题的最佳答案。如果您只关心最高状态值,则无需检查每个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2017-04-23
    相关资源
    最近更新 更多