[英]While converting a list consist of string into float throws value error: could not convert string to float: '22.52.58.246'. How to convert into float?
I need to convert the strings from a list into float
values and append them to a new list.我需要将列表中的字符串转换为
float
值并将它们附加到新列表中。
But I get this error:但我收到此错误:
ValueError: could not convert string to float: '22.52.58.246'.
ValueError: 无法将字符串转换为浮点数:'22.52.58.246'。
How can I convert them into float?如何将它们转换为浮点数?
Time = [
'22.53.13.106',
'22.53.13.106',
'22.53.13.161',
'22.53.13.161',
'22.53.13.162'
]
for i in range(0, len(Time)):
Time[i] = float(Time[i])
22.53.13.106
is not a valid floating point value (a) as it appears to have more than one decimal point. 22.53.13.106
不是有效的浮点值(a),因为它似乎有一个以上的小数点。 They could be IPv4 addresses given no single component is greater than 255
, but you would have to check what's producing them to be sure.如果没有单个组件大于
255
,它们可能是 IPv4 地址,但您必须检查是什么产生它们才能确定。
Or, based on the fact that they're called Time
, they may well be hh.mm.ss.xxx
(xxx = milliseconds), in which case you need to decide first what units you want them in. For example, floating point hours would be something like:或者,基于它们被称为
Time
的事实,它们很可能是hh.mm.ss.xxx
(xxx = 毫秒),在这种情况下,您需要首先决定您希望它们采用的单位。例如,浮点数小时将是这样的:
def hh_mm_ss_MMM_to_hours(arg):
fields = arg.split(".")
if len(fields) != 4:
raise RuntimeError("WTF!")
ret_val = int(fields[0])
ret_val += int(fields[1]) / 60
ret_val += int(fields[2]) / 60 / 60
ret_val += int(fields[3]) / 60 / 60 / 1000
return ret_val
Time=['22.53.13.106', '22.53.13.106', '22.53.13.161', '22.53.13.161', '22.53.13.162']
for time in Time:
print(f"{time} -> {hh_mm_ss_MMM_to_hours(time)}")
That produces:这产生:
22.53.13.106 -> 22.88697388888889
22.53.13.106 -> 22.88697388888889
22.53.13.161 -> 22.886989166666666
22.53.13.161 -> 22.886989166666666
22.53.13.162 -> 22.886989444444445
(a) Unless you're one of those strange European types who can't seem to figure out the difference between a decimal point and a comma :-) (a)除非你是那些似乎无法弄清楚小数点和逗号之间区别的奇怪的欧洲人之一:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.