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

2024-03-28 19:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查列表中的所有元素,看看它们是否满足条件“小于5”。我要做的是,如果我的列表中没有小于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.

我怎样才能去掉输出的最后一行呢?你知道吗


Tags: noin元素列表for数字elements语句
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的内容,如果有,则运行循环。你知道吗

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

只有在遇到break时才会跳过elsefor-loop。因此,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.')

相关问题 更多 >