CG Nguyen
CG Nguyen

Reputation: 97

Cast list of string to different data type in python

I was wondering if there is a cleaner way to parse the following string:

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)

Upvotes: 2

Views: 564

Answers (3)

gkusner
gkusner

Reputation: 1244

you can build on B.M. s answer to get ALL the fields and name them:

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'

Upvotes: 0

B. M.
B. M.

Reputation: 18628

Perhaps a bit more readable by expliciting converters :

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]

Upvotes: 6

alecxe
alecxe

Reputation: 473863

You can use numpy.genfromtxt() to automatically detect data types (inspired by this answer) - specify the dtype as None and set the appropriate delimiter:

>>> 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

Upvotes: 5

Related Questions