HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Putting a matrix from a text file into a list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fileintotextputtinglistfrommatrix

Problem

I'm trying to read a text file with matrix and put it in a list, but I am using two loops here and I want my function to be faster.

def read_file(path_to_file):
    mylist=[]
    for eachLine in open(path_to_file,'rt'):
        mylist.append([int(eachRow) for eachRow in eachLine.split()])
    return mylist

Solution

Not sure if it's possible to make this faster. But it can be better:

with open(path_to_file, 'rt') as fh:
    return [[int(value) for value in line.split()] for line in fh]


First of all, you should always use a with ... context manager when working with files. That way you cannot forget to close the file handle after you are done reading from it.

Other improvements:

  • More natural variable names



  • Simpler and more compact writing style using a list comprehension



Also keep in mind PEP8, the Python style guide.

Code Snippets

with open(path_to_file, 'rt') as fh:
    return [[int(value) for value in line.split()] for line in fh]

Context

StackExchange Code Review Q#122745, answer score: 3

Revisions (0)

No revisions yet.