我想跳过字符串元素和浮点类型的乘法。我想避免零分割错误。所以我尝试下面的代码。如何在计算中跳过列表中的sting元素?
x =[5,2,0.2,-2,1]
y=[4,3,2,1,0]
z=[m/n if m and n !=0 else "Na" for m,n in zip(x,y)]
print(z)
a=[i*0.5 if i != str else 0 for i in z]
print(a)
当我运行上面的代码。我得到了这个结果。
[1.25, 0.6666666666666666, 0.1, -2.0, 'Na']
Traceback (most recent call last):
a=[i*0.5 if i != str else 'Na' for i in z]
TypeError: can't multiply sequence by non-int of type 'float'
Process finished with exit code 1enter code here
我想达到的目标是: A = [0.625,0.3333333333333333,0.05,-1.0, '娜']
请点我了我该怎么办。谢谢你的帮助。
'[[i * 0.5 if is not isinstance(i, str)else'Na'for i in s]' –