如果列表中的整数为零,如何跳过字符串创建?

How to skip string creation if the the integer in a list is a zero?

在此示例代码中,有时“差异”为 0。如何删除差异为 0 的 'statements'? (详情见下文)

classlist = ['CLASS1', 'CLASS2', 'CLASS3', 'CLASS4', 'CLASS5', 'CLASS6', 'CLASS7']
gradelist1 = ['69.8', '73', '89', '0', '93', '57']
gradelist2 = ['95.3', '79', '84', '0', '68', '63']

def gradeChangeShow():
    difference = []
    try:
        for i in range(len(gradelist1)):
            difference.append(int(float(gradelist2[i])) - float(gradelist1[i]))
        difference = ["{:.1f}".format(x) for x in difference]
    except ValueError:
        difference.append('0')
    difference = [x for x in difference if x != '0']
    statement = [f'\n{c.rstrip()}: {d}' for c, d in zip(classlist, difference)]
    comma_delete = ','.join(statement)
    return comma_delete.replace(',', '')

print(gradeChangeShow())

这是上面代码的结果:

CLASS1: 25.2 
CLASS2: 6.0  
CLASS3: -5.0 
CLASS4: 0.0  
CLASS5: -25.0
CLASS6: 6.0

我希望它如何出现:

CLASS1: 25.2 
CLASS2: 6.0  
CLASS3: -5.0 
CLASS5: -25.0
CLASS6: 6.0

当您尝试过滤结果时,您使用了整数 0 值作为目标。由于您的值是带小数点的字符串,因此这对您来说是行不通的。

相反,请确保与相同类型进行比较。您可以针对 '0.0' 进行过滤,但如果您更改字符串中的精度,这将失败。我建议您将该值转换为数字,并与之进行比较。

statement = [f'\n{c.rstrip()}: {d}'
               for c, d in zip(classlist, difference) if float(d) != 0]

输出:

CLASS1: 25.2
CLASS2: 6.0
CLASS3: -5.0
CLASS5: -25.0
CLASS6: 6.0