2011-11-22 71 views
4

我得到的数据类型<type 'unicode'>将unicode字符串更改为列表?

u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' 

我想转换此列出像

[0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22] 

我怎样才能做到这一点与Python?

谢谢

回答

8

就像这样:

>>> a = u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' 
>>> [float(i) for i in a.strip('{}').split(',')] 
[0.128, 0.128, 0.133, 0.137, 0.141, 0.146, 0.15, 0.155, 0.159, 0.164, 0.169, 0.174, 0.179, 0.185, 0.19, 0.196, 0.202, 0.208, 0.214, 0.22] 

Unicode是非常相似的str,你可以使用.split(),以及strip()。此外,铸造到float的工作方式为str

所以,首先通过使用.strip('{}')剥离您的不必要的大括号({})的串,然后分裂,通过使用.split(',')逗号(,)生成的字符串。之后,您可以使用列表理解,将每个项目转换为float,如上例所示。

+1

只是我想要的方式,感谢您的帮助很大:) – daydreamer

+2

@daydreamer:我很高兴我帮助:) – Tadeck

4

出我的头和未经考验的:

data = u'your string with braces removed' 
aslist = [float(x) for x in data.split(',')] 
相关问题