简体   繁体   English

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

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

I am trying to check all elements in a list to see if they meet the condition "less than 5".我正在尝试检查列表中的所有元素,看看它们是否满足“小于 5”的条件。 What I'm trying to do is if no numbers in my list are less than 5, I want to print a statement "There are no elements in this list less than 5.", otherwise print only those numbers that are, and not "There are no elements in this list less than 5."我想要做的是,如果我的列表中没有数字小于 5,我想打印一条语句“此列表中没有小于 5 的元素。”,否则只打印那些数字,而不是“此列表中没有小于 5 的元素。” also.还。

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

This produces the output:这将产生输出:

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

How can I get rid of the last line of that output?我怎样才能摆脱该输出的最后一行?

The else of a for-loop will only be executed if no break was encountered.只有在没有遇到break时才会执行for-loopelse Thus, a for-else statement is not appropriate for finding multiple elements in a list since the first break will stop the loop.因此, for-else语句不适用于在列表中查找多个元素,因为第一个break将停止循环。

Instead, use a list-comprehension and print accordingly based on the result.相反,使用列表理解并根据结果相应地打印。

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

You could do something like:您可以执行以下操作:

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)

This checks if your list contains anything greater than 5 before anything, and if there is, then it runs your loop.这将检查您的列表是否包含任何大于 5 的内容,如果有,则运行您的循环。

Keep a boolean flag outside the loop.在循环外保留一个布尔标志。 Set it to true if at least one element is found.如果至少找到一个元素,则将其设置为 true。 If the flag does not change- print out your statement about no elements being found greater than 5:如果标志没有改变 - 打印出关于没有发现大于 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")     

What you need is some sort of flag to keep track whether condition was met like in the code below.您需要某种标志来跟踪是否满足条件,如下面的代码所示。 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