python定义一个字符串数组_读文件字符串到一个数组(在Python的方式)

1586010002-jmsa.png

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.

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])

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.

解决方案

Quick answer:

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)

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]

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=' '))]

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))]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值