这是我的清单:
['-50.00', '60.00', '-63.00', '50.00', '-57.00']
我怎样才能用这个项目计算
-50.00+60.00-63.00+50.00-57.00
temp = ['-50.00', '60.00', '-63.00', '50.00', '-57.00']
sum(float(t) for t in temp)
还有一个选择:
>>> import decimal
>>> float(sum(decimal.Decimal(x) for x in temp))
-60.0
另一种将字符串转换为浮点数的方法是使用map
my_list = ['-50.00', '60.00', '-63.00', '50.00', '-57.00']
new_list = map(float, my_list)
结果:
>>> new_list
[-50.0, 60.0, -63.0, 50.0, -57.0]
>>> sum(new_list)
-60.0
你也可以使用 numpy 包:
>>> import numpy as np
>>> my_list = ['-50.00', '60.00', '-63.00', '50.00', '-57.00']
>>> np.sum(np.array(my_list).astype(np.float))
-60.0