读文件字符串到一个数组(在Python的方式) [英] Reading file string into an array (In a pythonic way)
问题描述
我读线,然后与他们合作。每一行由浮点数只由
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
我有pretty所有事情排序到线转换成数组。
I have pretty much everything sorted up to convert the lines into arrays.
我基本上做到(pseudopython code)
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])
这工作,击打似乎有点违反直觉和antipythonic,我想知道是否有更好的方法来处理从文件的输入有在最后一个数组满彩车的。
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]
如果你真的想让你的同事讨厌你,你可以让一个班轮(不是Python的所有: - ):
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
的refatoring潜力,我不会使用它,但它可以是好到足够多。这是这里的灰色地带,所以我不会说这是Python的,但它是definitly派上用场了。
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))]
这篇关于读文件字符串到一个数组(在Python的方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!