在python中将一串浮点数转换为浮点数组

时间:2014-03-07 06:17:34

标签: python arrays csv

我正在尝试读取csv文件并创建一组数据行的数组。这是我的代码:

import csv
def main():
    a = range(4)
    x = 0
    with open('test.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            a[x] = [float(x) for x in row.split()]
            x += 1
    print a 

输出:

[['13,4.2,2.4,5,6.4'], ['14,3.2,3.4,5.6,7.2'], ['15,8.5,3.7,8.5,0.75'], ['16,5.4,8.3,3.5,5.4']]

如何将这些数组从1个字符串转换为浮点数组?

2 个答案:

答案 0 :(得分:2)

我可以使用eval:

 >>> ls = [['13,4.2,2.4,5,6.4'], ['14,3.2,3.4,5.6,7.2'], ['15,8.5,3.7,8.5,0.75'],     ['16,5.4,8.3,3.5,5.4']]
 >>> [ eval(x[0]) for x in ls ]
 [(13, 4.2, 2.4, 5, 6.4), (14, 3.2, 3.4, 5.6, 7.2), (15, 8.5, 3.7, 8.5, 0.75), (16, 5.4,   8.3, 3.5, 5.4)]
 >>>

答案 1 :(得分:1)

直接回答你的问题:

x = [['13,4.2,2.4,5,6.4'], ['14,3.2,3.4,5.6,7.2'], ['15,8.5,3.7,8.5,0.75'], ['16,5.4,8.3,3.5,5.4']]
x = [float(q) for a in x for q in a[0].split(',')]

然而,更好的方法是在阅读时通过指定delimiter=','来分割它。

spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
a = [row for row in spamreader]
a = [x for sublist in a for x in sublist]