我正在尝试将 csv 文件作为这样的矩阵读取:
import csv
with open("data.csv", "r") as file:
table = [line for line in csv.reader(file)]
for line in table:
print(line)
但是,我需要将列表的内容转换为浮点数。我试图转换为 float 使用
table = [int(x) for x in table]
但是这是一个错误
TypeError: int() argument must be a string or a number, not 'list'
如何解决这个问题?
最佳答案
下面是一个简单的例子,如何将每行数据转换为float
数字类型并做一些计算:
假设 CSV 数据文件 data.csv
充满了一些ints
和 floats
:
12,13,14,15,16
0.1,0.2,0.3,0.4,0.5
import csv
with open("./data.csv", "rU") as file:
table = [line for line in csv.reader(file)]
for line in table:
numbers = [ float(x) for x in line ]
sum = 0
for number in numbers:
sum = sum + number
print(numbers)
print "The sum of numbers is: ", sum
输出:
[12.0, 13.0, 14.0, 15.0, 16.0]
The sum of numbers is: 70.0
[0.1, 0.2, 0.3, 0.4, 0.5]
The sum of numbers is: 1.5
关于python-2.7 - 如何将字符串列表从 csv 文件转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619644/