简体   繁体   English

使用 function 从 Python(无 numpy)中的 txt 文件读取矩阵

[英]Read matrix from txt file in Python (no numpy) using function

I am beginner and trying to Read a matrix from a text file and return it and use function read_matrix(pathname) but all that I can find and build it and it does not work.我是初学者,正在尝试从文本文件中读取矩阵并将其返回并使用 function read_matrix(pathname) 但我能找到并构建它的所有内容都不起作用。 Can you help me understand where I did wrong.你能帮我理解我哪里做错了吗? Please no numpy请不要 numpy

def read_matrix(pathname):
matrices=[]
m=[]
for line in file("matrix.txt",'r'):
   if line=="1 1\n": 
      if len(m)>0: matrices.append(m)
      m=[]
   else:
      m.append(line.strip().split(' '))
if len(m)>0: matrices.append(m)
return(m)
m = read_matrix('matrix.txt') 

if your file looks like this:如果您的文件如下所示:

data.txt:

1 2 3
4 5 6
7 8 9

you can read it to a matrix (list of lists) as follow:您可以将其读入矩阵(列表列表),如下所示:

with open("data.txt") as fid:
    txt=fid.read()


matrix = [[int(val) for val in line.split()] for line in txt.split('\n') if line]

your code could work as follow, however there are some lines which could be written better:您的代码可以按如下方式工作,但是有些行可以写得更好:

def read_matrix(pathname):
    matrices = []
    m = []
    for line in open(pathname,'r'):
        if line=="1 1\n": 
            if len(m) > 0: 
                matrices.append(m)
                m=[]
        else:
            m.append(line.strip().split(' '))
    if len(m)>0: matrices.append(m)
    return(m)

m = read_matrix('data.txt')

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

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