将文件字符串读入数组(以pythonic方式) [英] Reading file string into an array (In a pythonic way)

查看:52
本文介绍了将文件字符串读入数组(以pythonic方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文件中读取行然后使用它们.每行仅由浮点数组成.

I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.

我已经整理好几乎所有东西,以便将行转换为数组.

I have pretty much everything sorted up to convert the lines into arrays.

我基本上做(伪python代码)

I basically do (pseudopython code)

 line=file.readlines()
 line=line.split(' ') # Or whatever separator
 array=np.array(line)
 #And then iterate over every value casting them as floats
      newarray[i]=array.float(array[i])

这行得通,但是似乎有点违反直觉和反Python,我想知道是否有更好的方法来处理来自文件的输入以在最后得到一个充满浮点数的数组.

This works, buts seems a bit counterintuitive and antipythonic, I wanted to know if there is a better way to handle the inputs from a file to have at the end an array full of floats.

推荐答案

快速回答:

arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
    # use a list comprehension to build your array on the fly
    new_array = np.array((array.float(i) for i in line.split(' '))) 
    arrays.append(new_array)

如果您经常处理此类数据,csv 模块会有所帮助.

If you process often this kind of data, the csv module will help.

import csv

arrays = []
# declare the format of you csv file and Python will turn line into
# lists for you 
parser = csv.reader(open(your_file), delimiter=' '))
for l in parser: 
    arrays.append(np.array((array.float(i) for i in l)))

如果你觉得很狂野,你甚至可以完全声明:

If you feel wild, you can even make this completly declarative:

import csv

parser = csv.reader(open(your_file), delimiter=' '))
make_array = lambda row : np.array((array.float(i) for i in row)) 
arrays = [make_array(row) for row in parser]

如果你真的想让你的同事讨厌你,你可以制作一个班轮(根本不是 PYTHONIC :-):

And if you realy want you colleagues to hate you, you can make a one liner (NOT PYTHONIC AT ALL :-):

arrays = [np.array((array.float(i) for i in r)) for r in csv.reader(open(your_file), delimiter=' '))]

去掉所有的样板和灵活性,您最终可以得到一个干净且可读性强的衬里.我不会使用它,因为我喜欢使用 csv 的重构潜力,但它已经足够了.这是一个灰色地带,所以我不会说它是 Pythonic,但它绝对很方便.

Stripping all the boiler plate and flexibility, you can end up with a clean and quite readable one liner. I wouldn't use it because I like the refatoring potential of using csv, but it can be good enought. It's a grey zone here, so I wouldn't say it's Pythonic, but it's definitly handy.

arrays = [np.array((array.float(i) for i in l.split())) for l in open(your_file))]

这篇关于将文件字符串读入数组(以pythonic方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆