简体   繁体   English

将字符串列表转换为数据文件中的浮点数

[英]Converting list of strings to floats from data file

my code produces this result 我的代码产生了这个结果

[['1.2', ' 4.3', ' 7', '0'], ['3', ' 5', ' 8.2', '9'], ['4', ' 3', ' 8', '5.6'], ['8', ' 4', ' 3', '7.4']]

but i want to remove the ' ' 但我想删除''

def main():
    my_list = [line.strip().split(',') for line in open("Alpha.txt")]
    print(my_list)


main()

i attempted to convert the list into floats but it keeps returning errors. 我试图将列表转换为浮点数,但它不断返回错误。 I need a way to convert the current list in this format into floats. 我需要一种将这种格式的当前列表转换为浮点数的方法。

[float(i) for i in lst]

this hasnt worked for me because it seems to error out when trying to use float(my_list) 这对我没有用,因为在尝试使用float(my_list)时似乎出错了

You want [[float(i) for i in j] for j in lst] instead of [float(i) for i in j] , the list is nested - you have a list of list of floats, not just a list of floats like you would need for your code to work. 您希望[[float(i) for i in j] for j in lst]而不是[float(i) for i in j]中的列表是嵌套的-您有一个float列表的列表,而不仅仅是就像您的代码正常工作一样需要浮动。 Also, it would be better to open the file with a with statement, and you might want to use a try ... except ... to catch exceptions in case some of the numbers in the file can't be turned into floats - eg. 另外,最好使用with语句打开文件,并且您可能希望使用try ... except ...来捕获异常,以防文件中的某些数字不能转换为浮点数-例如。 if one line is 1, 2, 34, 56thiswillcrashyourprogramatthemoment, 7, 8, 9 . 如果一行是1, 2, 34, 56thiswillcrashyourprogramatthemoment, 7, 8, 9

In your case, i is gonna be ['1.2', ' 4.3', ' 7', '0'] and obviously, you can't float a list! 在您的情况下, i将是['1.2', ' 4.3', ' 7', '0'] ,显然,您不能浮动列表!

Well, you'll have to use a double iteration: 好吧,您将不得不使用两次迭代:

[[float i for i in j] for j in my_list]

Hope this helps!! 希望这可以帮助!!

You can use map to cast those strings in floats 您可以使用map将这些字符串转换为float

my_list = map(lambda item: ( map ( lambda s: float(s), item ) ), my_list)

You will get some fancy numbers due to python precision 由于python精度,您会得到一些花哨的数字

>>> map(lambda item: (map(lambda s: float(s), item)), l)

[[1.2, 4.2999999999999998, 7.0, 0.0], [3.0, 5.0, 8.1999999999999993, 9.0], [4.0, 3.0, 8.0, 5.5999999999999996], [8.0, 4.0, 3.0, 7.4000000000000004]] [[1.2,4.2999999999999998,7.0,0.0],[3.0,5.0,8.1999999999999993,9.0],[4.0,3.0,8.0,5.5999999999999996],[8.0,4.0,3.0,7.4000000000000004]]

If you are planning on doing calculations with your data, you might consider numpy and import using numpy.genfromtxt : 如果您打算对数据进行计算,则可以考虑使用numpy并使用numpy.genfromtxt导入:

import numpy as np
my_array = np.genfromtxt('Alpha.txt',delimiter=',')

If required, this could be converted to a list like so: 如果需要,可以将其转换为如下列表:

my_list = my_array.tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM