本文介绍如何高效遍历数值列表,筛选满足阈值条件的元素,并在无一满足时输出自定义提示信息,避免冗余逻辑与重复遍历。
在实际数据处理中,我们常遇到这样的需求:从一组数值中提取出达到指定阈值(比如0.8)的项,同时要求当没有任何元素达标时给出明确的反馈——而不是默默地返回一个空列表。原始代码虽然能完成筛选,但缺少一个“兜底响应”机制。下面提供一种清晰、高效且符合Python惯用风格的实现方案。
✅ 推荐写法:一次遍历 + 布尔判空
scores = [0.9, 0.8, 0.3, 0.4]
threshold = 0.8
filtered = []
for score in scores:
if score >= threshold: # 注意:题目要求“大于0.8”实际应包含边界值0.8,因此使用≥
filtered.append(score)
if filtered:
print(filtered) # 输出: [0.9, 0.8]
else:
print("None of the scores in the list met the threshold")
