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

2024-07-01 08:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道有没有更干净的方法来解析以下字符串:

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)

Tags: 方法key字符串idlinefloatintseries
3条回答

您可以在B.M.s.答案的基础上生成所有字段并将其命名:

line = "NOVEL_SERIES, 3256432, 8, 1, 2.364, 4.5404, 9.8341"
types=[str,int,int,int,float,float,float]
key, id, xval, yval, est1, est2, est3 = [f(x) for (f,x) in zip(types,line.split(', '))]

>>> [key, id, xval, yval, est1, est2, est3]
['NOVEL_SERIES', 3256432, 8, 1, 2.364, 4.5404, 9.8341]
>>> key
'NOVEL_SERIES'

您可以使用^{}自动检测数据类型(灵感来自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

通过明确说明转换器,也许更易读:

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]

相关问题 更多 >

    热门问题