我想跳過字符串元素和浮點類型的乘法。我想避免零分割錯誤。所以我嘗試下面的代碼。如何在計算中跳過列表中的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]' –