【问题标题】:How not to execute else statement of for-loop when if statement is satisfied at least once?当if语句至少满足一次时,如何不执行for循环的else语句?
【发布时间】:2018-11-04 01:33:53
【问题描述】:

我正在尝试检查列表中的所有元素,看看它们是否满足“小于 5”的条件。我想要做的是,如果我的列表中没有数字小于 5,我想打印一条语句“此列表中没有小于 5 的元素。”,否则只打印那些数字,而不是“此列表中没有小于 5 的元素。”也。

list = [100, 2, 1, 3000]
for x in list:
    if int(x) < 5:
        print(x)
else:
    print("There are no elements in this list less than 5.")

这会产生输出:

2
1
There are no elements in this list less than 5.

我怎样才能摆脱该输出的最后一行?

【问题讨论】:

    标签: python python-3.x for-else


    【解决方案1】:

    只有在遇到 break 时才会跳过 for-loopelse。因此,for-else 语句不适合在列表中查找多个元素。

    相反,使用列表理解并根据结果进行相应的打印。

    lst = [100, 2, 1, 3000]
    
    less_than_five = [x for x in lst if x <  5]
    
    if less_than_five:
        print(*less_than_five)
    else:
        print('There are no elements in this list greater than 5.')
    

    【讨论】:

      【解决方案2】:

      在循环外保留一个布尔标志。如果至少找到一个元素,则将其设置为 true。如果标志没有改变 - 打印出关于没有发现大于 5 的元素的声明:

      list = [100, 2, 1, 3000]
      found = False
      for x in list:
        if int(x) < 5:
          print(x)
          found = True
      
      if found == False:
        print("There are no elements in this list greater than 5")     
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        if max(mylist) < 5:
            print('there are no elements in this list greater than 5')
        else:
            for x in mylist:
                if int(x) < 5:
                    print(x)
        

        这会检查您的列表是否包含任何大于 5 的内容,如果有,则运行您的循环。

        【讨论】:

        • 这将导致遍历列表两次,一次找到最大值,一次进行打印
        【解决方案4】:

        您需要某种标志来跟踪是否满足条件,如下面的代码所示。 list = [100, 2, 1, 3000] flag = False for x in list: if int(x) < 5: print(x) flag = True if not flag: print("There are no elements in this list greater than 5.")

        【讨论】:

        • 您能否更详细地解释一下标志的工作原理,或者指导我到可以自学的地方?
        • 该标志只是一个布尔触发器,只有在至少一个值满足以下 5 个条件时才会变为 True
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-20
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 2013-08-05
        相关资源
        最近更新 更多