ialsafid ialsafid - 1 year ago 71
Python Question

Read txt and put in matrix in python

In my txt I have this:


I want to place each line of text file as a row of a matrix, and each 0 and 1 is an array element. For example, M [0] = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ]

And then I could access M[1][1], which contain 0.

Recently I brought a similar question here in the forum and the staff helped me with very lean code and solved very well. The goal was to turn into one list. Follows the code bellow:

with open ( 'arq.txt') the buffer:
l = list (map (int, buffer.read (). replace ('\ n', '')))
print l

Besides my doubt someone could pass me some website with reference to the functions, or a book you already have experiment and recommended for beginner, intermediate. Video lessons. I tried searching on google some website like the http://www.cplusplus.com/reference/ but found nothing similar to the python. The official python does not have examples from each function.

Answer Source

You can try this:

with open ( 'arq.txt') as buffer:
    mat = list(map(int, line.strip()) for line in buffer)
print mat
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download