我将数据设为类型<type '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做到这一点?
谢谢
答案 0 :(得分: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 :(得分:4)
从我的头脑中未经测试:
data = u'your string with braces removed'
aslist = [float(x) for x in data.split(',')]