在python中将字符串列表强制转换为不同的数据类型
我想知道是否有更干净的方法来解析以下字符串:在python中将字符串列表强制转换为不同的数据类型,python,split,casting,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) 您可以
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)
您可以使用自动检测数据类型(灵感来自)-将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.的答案获取所有字段并命名它们:
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'
你的目标到底是什么?我想你的意思是
line.split(“,”)
?你可能也指xval=int(xval)
和yval=int(yval)
@idjaw肯定是一样的,但我们也应该永远记住“显式优于隐式”。哇……这是一个非常有趣的方法。干得好我有一个问题,因为我是Python新手,只是想了解:为什么x('10.9')和float('10.9')都返回相同的值?>>x>>>x('10.9')10.9>>>浮点(10.9)10.9我不明白这里x是什么?B.M.请看我刚才在下面添加的更好的格式问题