在我的python代码中,我搜索一个特定的格式,然后返回浮点数,即
...
return {'ID': int(dataINgood[0]),
'mIdx': int(dataINgood[2])-1,
'Px' : float(dataINgood[6]),
'Py' : float(dataINgood[7]),
'Pz' : float(dataINgood[8]),
'E' : float(dataINgood[9]),
'M' : float(dataINgood[10])}
我想要的是做一些事情
'Pt' : math.sqrt(float( dataINgood[6] * dataINgood[6]) + float(dataINgood[7]*dataINgood[7]))
但是会返回
'Pt' : math.sqrt(float( dataINgood[6] * dataINgood[6]) + float(dataINgood[7]*dataINgood[7])) }
TypeError: can't multiply sequence by non-int of type 'str'
任何提示?
感谢
答案 0 :(得分:1)
因为dataINgood
是list
的{{1}}。您需要将值转换为strings
:
float
答案 1 :(得分:1)
投射一切,然后工作:
fs = [float(x) for x in dataINgood]
{... 'Pt' : math.sqrt(fs[6]**2 + fs[7]**2) }
顺便说一句,这是更好的:
{... 'Pt' : math.hypot(fs[6], fs[7]) }
所以你的代码看起来像这样:
fs = [float(x) for x in dataINgood]
return {'ID': int(fs[0]),
'mIdx': int(fs[2])-1,
'Px' : fs[6],
'Py' : fs[7],
'Pz' : fs[8],
'E' : fs[9],
'M' : fs[10],
'Pt' : math.hypot(fs[6], fs[7])
}
答案 2 :(得分:0)
math.sqrt(float( dataINgood[6] * dataINgood[6]) + float(dataINgood[7]*dataINgood[7]))
你需要在乘法之前将dataINgood [x]转换为float,所以你应该尝试下面的语法
**math.sqrt((float(dataINgood[6]) * float(dataINgood[6])) + (float(dataINgood[7])* float(dataINgood[7])))**