Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string separated by commas to a list of floats

Tags:

python

list

In Python, I currently have a one element list of elements given like so:

x= ['1.1,1.2,1.6,1.7']

where each of the values are only separated by commas. I want to make this a list of floats, e.g like

x=[1.1, 1.2, 1.6, 1.7]

I've tried x=[float(i) for i in x] and x=[float(i) for i in x.split()], but both return errors.

like image 700
Sheel Stueber Avatar asked Feb 06 '23 10:02

Sheel Stueber


1 Answers

x is a list with one string, so to access that string you need x[0]. That string is comma-separated, so you need to specify the delimiter: split(','). (Otherwise, split() tries to split a string on whitespace, as described in the docs.)

So you end up with:

[float(i) for i in x[0].split(',')]
like image 144
user812786 Avatar answered Feb 08 '23 15:02

user812786