简体   繁体   English

将一串float转换为python中的float数组

[英]converting a string of floats into float array in python

I am trying to read a csv file and make an array of arrays of the rows of data. 我正在尝试读取一个csv文件,并使数据行的数组的数组。 Here is my code: 这是我的代码:

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 

Output: 输出:

[['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']]

How do I turn these arrays from 1 string into an array of floats? 如何将这些数组从1个字符串转换为浮点数组?

Can I use eval: 我可以使用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)]
 >>>

Directly answering your question: 直接回答您的问题:

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(',')]

However, much better would be to split it when reading by specifying delimiter=',' . 但是,更好的方法是在读取时通过指定delimiter=','将其拆分。

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

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

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