开发者

converting strings to numeric

开发者 https://www.devze.com 2023-02-28 05:48 出处:网络
What\'s a simple way to convert stings into numerics: from: [\'3.65e+03\', \'1.14e+04\', \'1.35e+04\', \'1.46e+04\']

What's a simple way to convert stings into numerics:

from:

['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']

to:

开发者_运维知识库
[3.65e+03, 1.14e+04, 1.35e+04, 1.46e+04]

Thanks.


First off, I hope you are aware of the limitations in representing the floating point accurately in our current architectures.

The simple way for conversion is simply this.

>>> s = ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']
>>> map(float,s) 
>>> [3650.0, 11400.0, 13500.0, 14600.0]

But float rounds them off to the nearest value and it's representation does not matter as long as values are same. Sometimes, those values can have near-equal representation with same value (almost) for e.g.

>>> s = ['3.65e+93', '1.14e+04', '1.35e+04', '1.46e+04']
>>> map(float,s)
[3.6500000000000001e+93, 11400.0, 13500.0, 14600.0]

Update - Please see John Machin's comment for this behavior/repr.

But if you want exact representation, for e.g. if you are dealing calculations involving money, then you may want to use the Decimal type instead of float, which for all purposes can behave in the same way as your float.

>>> from decimal import Decimal
>>> map(Decimal,s)
[Decimal('3.65E+93'), Decimal('1.14E+4'), Decimal('1.35E+4'), Decimal('1.46E+4')]


map(float, your_list)

or

[float(x) for x in your_list]

Update For an explanation of why an unqualified recommendation to "use decimal" is not a good idea, see my answer to another question.


numbers = [eval(s) for s in ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']]

eval's a bit of a hack, but it's pretty well guaranteed to work. (specific float is also a good approach.)

0

精彩评论

暂无评论...
验证码 换一张
取 消