当if语句至少满足一次时,如何不执行for循环的else语句?
How not to execute else statement of for-loop when if statement is satisfied at least once?
我正在尝试检查列表中的所有元素,看它们是否满足条件 "less than 5"。我想做的是,如果我的列表中没有数字小于 5,我想打印一个语句 "There are no elements in this list less than 5.",否则只打印那些数字,而不是 "There are no elements in this list less than 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.
如何删除该输出的最后一行?
你可以这样做:
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
时才会跳过 for-loop
的 else
。因此,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.')
您需要的是某种标志来跟踪是否满足条件,如下面的代码所示。
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.")
我正在尝试检查列表中的所有元素,看它们是否满足条件 "less than 5"。我想做的是,如果我的列表中没有数字小于 5,我想打印一个语句 "There are no elements in this list less than 5.",否则只打印那些数字,而不是 "There are no elements in this list less than 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.
如何删除该输出的最后一行?
你可以这样做:
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
时才会跳过 for-loop
的 else
。因此,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.')
您需要的是某种标志来跟踪是否满足条件,如下面的代码所示。
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.")