简体   繁体   English

将字符串值转换为浮点数

[英]Convert string values to floating point

My small script returns a comma separated list of 10 floating point values, loops through them, and holds them in variable vals . 我的小脚本返回一个逗号分隔的10个浮点值列表,循环遍历它们,并将它们保存在变量vals

I sum these up into new variable 'total' like this: 我将这些总结为新的变量“总计”,如下所示:

total = sum(map(float, vals))

Easy enough, BUT oftentimes None occurs as one or more values in the list, 很简单,但列表中的一个或多个值通常None发生,

4.234,None,0.2398,None,None,0.0166666666667,None,None,None,None

then I get the ValueError: 然后我得到ValueError:

ValueError: could not convert string to float: N

How can I convert these None values to 0 so that the values sum up without error? 如何将这些None值转换为0,以使这些值求和而不会出错?

total = sum(map(float, filter(None,vals)))

From the docs: 从文档:

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None. 请注意,如果function不为None,则filter(function,iterable)等效于[如果function(item),则为iterable中的项目的项目];如果function为None,则等于[如果item,则为inererable中的项目的项目]。

If vals is a string literal (as DSM hints it looks like it is) use can use the ast library 如果vals是字符串文字(如DSM所暗示的那样),则可以使用ast

>>> vals = '[4.234,None,0.2398,None,None,0.0166666666667,None,None,None,None]'
>>> import ast
>>> vals_list = ast.literal_eval(vals)
>>> vals_list
[4.234, None, 0.2398, None, None, 0.0166666666667, None, None, None, None]

Then you can simply apply sum and filter 然后您可以简单地应用sumfilter

>>> total = sum(filter(None,vals_list))
>>> total
4.4904666666667

Note -- I did append square brackets to the string, so if they are missing that would be a step you would need 注意-我确实将方括号附加到了字符串上,因此如果缺少方括号,则需要执行此步骤

total = sum(float(val) for val in vals if val is not None)
sum(map(lambda x: float(x) if x else 0.0, vals))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM