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
Getting the Class Name of an Instance
Download File from Web in Python 3
Convert Excel Style Date with Pandas
Making Object JSON Serializable with Regular Encoder
Plot a Horizontal Line on a Given Plot
How to Find Median and Quantiles Using Spark
Can Not Click on a Element: Elementclickinterceptedexception in Splinter/Selenium
How to Print Pandas Dataframe Without Index
Create a Directly-Executable Cross-Platform Gui App Using Python
How to Install Python3 Version of Package via Pip on Ubuntu
Python Analog of PHP's Natsort Function (Sort a List Using a "Natural Order" Algorithm)
Pandas: Drop Consecutive Duplicates