ksp585 ksp585 -4 years ago 134
Python Question

Convert list elements to numbers

There is a csv file with the below three lines.

8.84,17.22,13.22,3.84
3.99,11.73,19.66,1.27
16.14,18.72,7.43,11.09


I am writing a function which reads lines from a file and appends it to an empty list so that I can use that list for computing mean.

Below is the code I wrote:

def my_calc(filename):
mydata = []
for line in open(filename).readlines():
mydata = mydata + line.strip().split(',')
return mydata


Here is the output:

['"8.84', '17.22', '13.22', '3.84"', '"3.99', '11.73', '19.66', '1.27"', '"16.14', '18.72', '7.43', '11.09"']


The list elements are strings. How can I convert these to float numbers?

I tried
map()
but I am getting an error message 'could not convert
string
to
float
'.

Thank you!

Answer Source

Try this :

a = ['"8.84', '17.22', '13.22', '3.84"', '"3.99', '11.73', '19.66', '1.27"', '"16.14', '18.72', '7.43', '11.09"']
result = map(float, map(lambda x : x.strip('"'), a))

Output :

[8.84, 17.22, 13.22, 3.84, 3.99, 11.73, 19.66, 1.27, 16.14, 18.72, 7.43, 11.09]

In case of python3, do this :

result = list(map(float, map(lambda x : x.strip('"'), a)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download