[英]Convert list elements to numbers
There is a csv file with the below three lines. 有一个包含以下三行的csv文件。
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
'. 我尝试了
map()
但收到一条错误消息“无法将string
转换为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 : 如果是python3,请执行以下操作:
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. https://repl.it/G9oO我不喜欢lambda,这可以为您提供帮助。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.