将数据读入二维数组? [英] Read data into 2 dimensional array?
本文介绍了将数据读入二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数据文件读入二维数组. 例如:
I am trying to read a data file into a 2 dimensional array. For example:
file.dat
:
1 2 3 a
4 5 6 b
7 8 9 c
我尝试过类似的事情:
file=open("file.dat","r")
var = [[]]
var.append([j for j in i.split()] for i in file)
但这没用.
我需要二维数组形式的数据,因为之后我需要对每个元素进行操作,例如
I need the data in form of two dimensional array as I need to do operations with each element afterwards, e.g.
for k in range(3):
newval(k) = var[k,1]
有什么想法吗?
推荐答案
file = open("file.dat", "r") # open file for reading
var = [] # initialize empty array
for line in file:
var.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array
# thus creating an array of arrays.
file.close() # close file.
这篇关于将数据读入二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文