2024-07-01 08:41:02 发布
网友
我想知道有没有更干净的方法来解析以下字符串:
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)
您可以在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,并设置适当的分隔符:
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]
您可以在B.M.s.答案的基础上生成所有字段并将其命名:
您可以使用^{} 自动检测数据类型(灵感来自this answer)-将
dtype
指定为None
,并设置适当的分隔符:通过明确说明转换器,也许更易读:
相关问题 更多 >
编程相关推荐