How to to read a matrix from a given file?

前端 未结 7 628
傲寒
傲寒 2020-12-09 17:41

I have a text file which contains matrix of N * M dimensions.

For example the input.txt file contains the following:



        
相关标签:
7条回答
  • 2020-12-09 18:01

    You can do this:

    fin = open('input.txt','r')
    a=[]
    for line in fin.readlines():
        a.append( [ int (x) for x in line.split(',') ] )
    
    0 讨论(0)
  • 2020-12-09 18:03

    The following does what you want:

    l = []
    with open('input.txt', 'r') as f:
      for line in f:
        line = line.strip()
        if len(line) > 0:
          l.append(map(int, line.split(',')))
    print l
    
    0 讨论(0)
  • 2020-12-09 18:08

    Consider

    with open('input.txt', 'r') as f:
        l = [[int(num) for num in line.split(',')] for line in f]
    print(l)
    

    produces

    [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 1, 0, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 1, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]]
    

    Note that you have to split on commas.


    If you do have blank lines then change

    l = [[int(num) for num in line.split(',')] for line in f ]
    

    to

    l = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ]
    
    0 讨论(0)
  • 2020-12-09 18:13

    You should not write your csv parser, consider the csv module when reading such files and use the with statement to close after reading:

    import csv
    
    with open('input.txt') ad f:
        data = [map(int, row) for row in csv.reader(f)]
    
    0 讨论(0)
  • 2020-12-09 18:18
    import numpy as np
    f = open ( 'input.txt' , 'r')
    l = []
    l = np.array([ line.split() for line in f])
    print (l)
    type(l)
    

    output:

    [['0']  ['0']  ['0']  ['0,0,0,0,0,0,0,0,0,0,0'] 
        ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'] 
    ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0']] 
    

    numpy.ndarray

    0 讨论(0)
  • 2020-12-09 18:23

    Check out this small one line code for reading matrix,

    matrix = [[input() for x in range(3)] for y in range(3)]
    

    this code will read matrix of order 3*3.

    0 讨论(0)
提交回复
热议问题