在python中将字符串列表转换为不同的数据类型

时间:2016-02-26 16:25:55

标签: python split casting

我想知道是否有更简洁的方法来解析以下字符串:

line = "NOVEL_SERIES, 3256432, 8, 1, 2.364, 4.5404, 9.8341"
key, id, xval, yval, est1, est2, est3 = line.split()
id   = int(id)
xval = int(value1)
yval = int(value2)
est1 = float(est1)
est2 = float(est2)
est3 = float(est3)

3 个答案:

答案 0 :(得分:6)

明确的转换器可能更具可读性:

In [29]: types=[str,int,int,int,float,float]

In [30]: [f(x) for (f,x) in zip(types,line.split(', '))]
Out[30]: ['NOVEL_SERIES', 3256432, 8, 1, 2.364, 4.5404]

答案 1 :(得分:5)

您可以使用numpy.genfromtxt()自动检测数据类型(受this answer启发) - 将dtype指定为None并设置相应的分隔符:

>>> import numpy as np
>>> from StringIO import StringIO
>>>
>>> buffer = StringIO(line)
>>> key, id, xval, yval, est1, est2, est3 = np.genfromtxt(buffer, dtype=None, delimiter=", ").tolist()
>>> key
'NOVEL_SERIES'
>>> id
3256432
>>> xval
8
>>> yval
1
>>> est1
2.364
>>> est2
4.5404
>>> est3
9.8341

答案 2 :(得分:0)

你可以建立在B.M.回答获取所有字段并命名它们:

messageId