[英]Convert empty strings of a list to float
I have a list of strings like this:我有一个这样的字符串列表:
grades = [['2.0', '3.67', '3.67', '2.33', '3.67', '2.0', '3.67', '2.33', '3.0', '2.33', '', '3.67', '2.33', '2.67', '3.0', '2.0', '4.0', '3.33', '4.0'],[...]]
and it contains grades but it also has empty items.它包含成绩,但也有空项目。 When I convert it to float it deletes those empty.
当我将它转换为浮动时,它会删除那些空的。
What I do is the following:我要做的是:
def try_convert(val):
try:
return float(val)
except ValueError as TypeError:
pass
floatGrades = [[float(z) for z in (try_convert(j) for j in i) if z] for i in grades]
Is there a way of turning the empty strings like this into 0?or None?有没有办法将这样的空字符串变成 0?或无?
I would prefer using the function only to check if is possible or not.我更喜欢使用 function 来检查是否可能。 With that you would be able to make the function more generic;
这样您就可以使 function 更通用; for general use:
一般用途:
grades = [['2.0', '3.67', '3.67', '2.33', '3.67', '2.0', '3.67', '2.33', '3.0', '2.33', '', '3.67', '2.33', '2.67', '3.0', '2.0', '4.0', '3.33', '4.0']]
def try_convert(val):
try:
float(val)
return True
except ValueError:
return False
# Get only values that can convert to float
result = [float(x) for values in grades for x in values if try_convert(x) == True]
# When can convert float(value) else None
result = [float(x) if try_convert(x) == True else None for values in grades for x in values ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.