In Python, How to Convert All of the Items in a List to Floats

In Python, how do I convert all of the items in a list to floats?

[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

How to convert string list into float list

list(map(float, word.split(':')))

This will convert each of the number to float

Changing all elements in a list to floats

The easiest fix is to parse the floating point values as you append them to the list:

list.append(float(lines[1]))

Convert list of lists of string into floats

x = [['1,10,300,0.5,85'], ['3,16,271,2.9,89']]

y = [[float(v) for v in r[0].split(',')] for r in x]

y will be

[[1.0, 10.0, 300.0, 0.5, 85.0], [3.0, 16.0, 271.0, 2.9, 89.0]]

Changing all strings except one in a list of lists to a float

for sublist in LofL:
for i in range(1, len(sublist)):
sublist[i]=float(sublist[i])

Explanation:
Your initial code sublist[1:]=float(sublist[1:] will not work as sublist[1:] is a list and you cannot turn list to a float.

So the for i in range(1, len(sublist) will iterate through each element in your sublist
then with each iteration we will convert sublist[i]=float(sublist[i] into float. Because you specified that the first item of sublist does not need to change hence we are starting our loop from 1



Related Topics



Leave a reply



Submit