[英]How to convert all the strings in a list of a list to floats
I've used this code to open a excel file, to create lists of each line of the excel file: 我已使用以下代码打开一个excel文件,以创建excel文件每一行的列表:
import csv
with open("csvfile.csv", "rb") as f:
lines = list(csv.reader(f))
>>> lines
[['0', '23.345', '-122.456'], ['1', '12.546', '-118.987'] ['2', '67.435', '-104.112']]
I do want to keep the lists of each line of the excel file in a bigger list, but I want each element to be floats rather than strings. 我确实希望将excel文件的每一行的列表都保留在更大的列表中,但是我希望每个元素都是浮点数而不是字符串。 What alteration would I have to make?
我必须进行哪些更改?
ie [[0, 23.345, -122.456], [1, 12.546, -118.987], [2, 67.435, -104.112]]
即
[[0, 23.345, -122.456], [1, 12.546, -118.987], [2, 67.435, -104.112]]
You may use nested list comprehension on your list of lists as: 您可以在列表列表上使用嵌套列表推导 :
>>> my_list = [['0', '23.345', '-122.456'], ['1', '12.546', '-118.987'], ['2', '67.435', '-104.112']]
>>> [[float(i) for i in sub_list] for sub_list in my_list]
[[0.0, 23.345, -122.456], [1.0, 12.546, -118.987], [2.0, 67.435, -104.112]]
Use map
in a list-comprehension while reading the file. 读取文件时,以列表方式使用
map
。
import csv
with open("csvfile.csv", "rb") as f:
lines = [map(float, line) for line in csv.reader(f)]
Saves you creating a list twice (reading, converting) 使您无需两次创建列表(阅读,转换)
You can use map()
with a list comprehension : 您可以将
map()
与列表推导一起使用 :
[map(float, sub_list) for sub_list in my_list]
Output: 输出:
>>> [map(float, sub_list) for sub_list in my_list]
[[0.0, 23.345, -122.456], [1.0, 12.546, -118.987], [2.0, 67.435, -104.112]]
Change: 更改:
lines = list(csv.reader(f))
into: 变成:
lines = [[float(x) for x in line] for line in csv.reader(f)]
ie: 即:
import csv
with open("csvfile.csv", "rb") as f:
lines = [[float(x) for x in line] for line in csv.reader(f)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.