[英]Turning strings in a list into floats
I have created a function that sorts through a csv file and returns lists into tuples however the items in the lists are string, how do I convert them to floats? 我创建了一个函数,通过csv文件进行排序并将列表返回到元组,但列表中的项目是字符串,如何将它们转换为浮点数?
I need to do calculations with this data such as mean, median etc. 我需要用这些数据进行计算,例如均值,中位数等。
def load_data(filename):
datasets = []
for line in open(filename):
line = line.strip().split(",")
dataset = ((line[0],line[1:]))
datasets.append(dataset)
return datasets
At the moment my data looks like this when printed ('Slow Loris', [' 21.72', ' 29.3', ' 20.08', ' 29.98',......
etc how do I remove the ' '
around the numbers 目前我的数据在打印时看起来像这样('Slow Loris', [' 21.72', ' 29.3', ' 20.08', ' 29.98',......
等等我如何删除数字周围的' '
You could make a new list and append the casted type like so... 您可以创建一个新列表并附加类似的类型...
list_of_floats = list()
for item in list_of_strings:
list_of_floats.append(float(item))
Or iterate through each value and change it at its current position... 或者遍历每个值并将其更改为当前位置...
for i in range(len(list_of_strings)):
list_of_strings[i] = float(list_of_strings)
def load_data(filename):
datasets = []
for line in open(filename):
line = line.strip().split(",")
floats = [float(x) for x in line[1:]]
dataset = ((line[0],floats))
datasets.append(dataset)
return datasets
Use the float() function to typecast it as a float. 使用float()函数将其类型化为float。
Per this link: Parse String to Float or Int 根据此链接:将字符串解析为Float或Int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.