[英]Python data unicode conversion
I have the following list: 我有以下列表:
list = [u'0', u'FF', u'7', u'0', u'FF', u'FFF', u'FFF']
and I need to use the elements as integer or float but when I try convevrting I get the following error: 我需要使用元素作为整数或浮点数,但当我尝试传播时,我得到以下错误:
>>> float(list[1])
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: could not convert string to float: FF
Is there any way of solving this? 有什么方法可以解决这个问题吗?
You can not convert that hex values to float
directly, instead you can convert to int with specifying a proper base using int()
function : 您不能将该十六进制值直接转换为
float
,而是可以使用int()
函数指定正确的base来转换为int:
>>> l = [u'0', u'FF', u'7', u'0', u'FF', u'FFF', u'FFF']
>>> [int(i,16) for i in l]
[0, 255, 7, 0, 255, 4095, 4095]
Or use float
on int
values : 或者在
int
值上使用float
:
>>> [float(int(i,16)) for i in l]
[0.0, 255.0, 7.0, 0.0, 255.0, 4095.0, 4095.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.