繁体   English   中英

当if语句至少满足一次时,如何不执行for循环的else语句?

[英]How not to execute else statement of for-loop when if statement is satisfied at least once?

我正在尝试检查列表中的所有元素,看看它们是否满足“小于 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.

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

只有在没有遇到break时才会执行for-loopelse 因此, for-else语句不适用于在列表中查找多个元素,因为第一个break将停止循环。

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

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.')

您可以执行以下操作:

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 的内容,如果有,则运行您的循环。

在循环外保留一个布尔标志。 如果至少找到一个元素,则将其设置为 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")     

您需要某种标志来跟踪是否满足条件,如下面的代码所示。 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.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM