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!
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)))
You can modify your function to append items as float only:
import re
def my_calc(filename):
mydata = []
for line in open(filename).readlines():
numbers = map(lambda x: float(x), re.sub("['\"]","",line).split(','))
mydata.append(numbers)
return mydata
That should give 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]]
list = ["8.84,17.22,13.22,3.84", "3.99,11.73,19.66,1.27", "3.99,11.73,19.66,1.27"]
result = []
for el in list:
strings = el.split(',')
floats = []
for el_s in strings:
floats.append(float(el_s))
result.append(floats)
print(result, type(result[0][0]))
https://repl.it/G9oO I'm bad with lambdas, this can help you.
Thank you for posting your answers!
Here's my solution. I took bits and pieces of all your solutions to come up with this one.
# Workable solution
mylist = []
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"']
for i in range(0,len(a)):
mylist.append(a[i].lstrip('"').rstrip('"'))
mylist = [float(x) for x in mylist]
print(mylist)
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.