简体   繁体   English

在python中解析矩阵的更有效方法?

[英]More efficient way to parse a matrix in python?

I have some data in a text file that looks like this: 我在文本文件中有一些数据,如下所示:

1895723957
8599325893
5723857831
5025852920

and I'd like to parse it into a list of lists in Python, so the output is 我想将其解析为Python中的列表列表,因此输出为

[[1, 8, 9, 5, 7, 2, 3, 9, 5, 7], [8, 5, ...

Right now, I have 现在,我有

data =  open('file.txt')
rows = [str(line).strip() for line in data]
matrix=[]
for r in rows:
    matrix.append(list(r))

but are there different ways to do this, such as using less lines of code or exploiting comprehensions? 但是有其他方法可以做到这一点,例如使用更少的代码行或利用理解力?

I've tried looking around, but I'm not exactly sure what keywords to use here... 我曾尝试环顾四周,但不确定在此使用什么关键字...

Thanks much! 非常感谢!

I'd try something like this: 我会尝试这样的事情:

with open('file.txt', 'r') as handle:
    matrix = [map(int, line.strip()) for line in handle]

I came up with the following way after playing around with comprehensions: 在玩弄理解后,我想出了以下方法:

data =  open('file.txt')
matrix = [[int(c) for c in row.rstrip()] for row in data]

rstrip is thanks to Blender above. rstrip感谢上面的Blender。

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

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