如果未满足阈值,我如何迭代此列表并返回文本?

问题描述 投票:0回答:2
scores = [0.9,0.8,0.3,0.4]
new=[]
for sc in scores:
    if sc < 0.8:
        pass
    else:
        new.append(sc)

print(new)

但是我还想包含一个响应,如果没有一个分数 >0.8,则打印“列表中的分数均未达到阈值” 我怎样才能有效地做到这一点?

python python-3.x
2个回答
0
投票

您可以采取多种方法来解决此问题。我将与您分享的方法定义变量或标志,如下所示。

scores = [0.9, 0.8, 0.3, 0.4]
new = []
threshold_met = False

for sc in scores:
    if sc >= 0.8:
        new.append(sc)
        threshold_met = True

if not threshold_met:
    print("None of the scores in the list had a score that met the threshold")
else:
    print(new)

即使满足单个条件,我们也知道存在满足阈值设置的数字,因此标志将设置为 True 表示相同,但如果没有,则默认标志为 False。


0
投票

您可以简单地检查列表末尾是否为空,例如:

scores = [0.9,0.8,0.3,0.4]
new=[]
for sc in scores:
    if sc < 0.8:
        pass
    else:
        new.append(sc)

if new:
    print(new)
else:
    print("none of the scores in list had a score that met threshold")

在 python 中,如果列表为空,则当类型转换为 bool 时,其值为 false。

© www.soinside.com 2019 - 2024. All rights reserved.