简体   繁体   English

阅读txt并放入python矩阵

[英]Read txt and put in matrix in python

In my txt I have this: 在我的txt中,我有:

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. 我想将文本文件的每一行放置为矩阵的一行,并且每个0和1是一个数组元素。 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 ] 例如,M [0] = [1,1,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 . 然后,我可以访问M [1] [1] ,其中包含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. 我尝试在Google上搜索一些网站,例如http://www.cplusplus.com/reference/,但没有找到与python类似的内容。 The official python does not have examples from each function. 官方python没有每个函数的示例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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