简体   繁体   中英

Read txt and put in matrix in python

In my txt I have this:

111111111111111111111
101000100000010000001
101011111011111110101

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.

Alright, this is quite simple actually. Not the best looking one liner code, but its easy to understand.

Try this:

m = {}
with open("args.txt") as f:
  data=f.read().split()
  for x in range(len(data)):
     m[x]=list(data[x])
print(m)
mat = [] with open('data.txt') as fin: for line in fin: row = [int(item) for item in line.strip()] mat.append(row)

You can try this:

with open ( 'arq.txt') as buffer:
    mat = list(map(int, line.strip()) for line in buffer)
print mat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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