简体   繁体   English

如何使用python从文件中读取数据到数组中?

[英]How to read data from file into array using python?

I need to somehow read data into array to preform calculations with each number. 我需要以某种方式将数据读入数组以执行每个数字的计算。

I have .txt file in following format. 我有以下格式的.txt文件。

4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

The structure depends on number in the first line, here it is 4 . 结构取决于第一行中的数字,这里是4 Meaning that it is 4x4 matrix. 表示它是4x4矩阵。

Now, I believe that to preform calculations calculations with each number it would be easiest to store matrix into two-dimensional array. 现在,我相信要对每个数字执行计算,将矩阵存储到二维数组中将是最简单的。 In that way each element would be accessible through array indices like this: 这样,每个元素都可以通过像这样的数组索引访问:

data[i][j]

Where data[4][3] = 16 其中data[4][3] = 16

How to fetch data into such array ? 如何获取数据到这样的数组? I'm in trouble here. 我在这里遇到麻烦了。

I tried following 我试过跟随

def get_data(file):

with open(file) as f:
    N = f.readline()
data = [line.strip('\n') for line in open(file)]

but it saves each line to the place of index. 但是它将每一行保存到索引位置。 So I have data[1] = ['1 2 3 4'] using this method. 所以我使用这种方法有data[1] = ['1 2 3 4']

Note that each number is separated by space and there is newline character \\n at the end of each line. 请注意,每个数字都由空格分隔,并且每行末尾都有换行符\\n

You're close. 你很亲密 You just need to go a step further and split each line you read in, into a separate list. 您只需要更进一步,将阅读的每一行分成一个单独的列表即可。 Additionally, you also need to convert your data into integers: 此外,您还需要将数据转换为整数:

def get_data(file):
    with open(file) as f:
        data = [line.split() for line in list(f)]
        return [[int(el) for el in line] for line in data]

you can open file in read mode with: 您可以使用以下方式以读取模式打开文件:

file = open("new_text", "r")

then, read each line in file as: 然后,将文件中的每一行读为:

for each_line in file:
    print(each_line)

to make a matrix you can write as: 要制作一个矩阵,可以这样写:

matrix = []

for each_line in file:
    matrix.append(each_line.split()) #each_line.split will make a array and then we append this in matrix

print(matrix)

Note, here as first element of the matrix we have 4 which is read from the file to remove the element we can use pop() method . 注意,这里作为矩阵的第一个元素,我们有4个元素可以从文件中读取,以删除元素,我们可以使用pop()方法。

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

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