我正在尝试检查列表中的所有元素,看它们是否满足“小于 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.
我怎样才能去掉该输出的最后一行?
请您参考如下方法:
for-loop 的 else 只有在没有遇到 break 时才会执行。因此,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.')
