3
\$\begingroup\$

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
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 13, 2016 at 16:20
\$\endgroup\$
1
  • \$\begingroup\$ Since the result will be a list of lists and int can handle only one number at a time, you have to have 2 loops of some sort. \$\endgroup\$ Commented Mar 15, 2016 at 1:37

1 Answer 1

3
\$\begingroup\$

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.

answered Mar 13, 2016 at 16:52
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.