简体   繁体   English

在python3中快速从txt文件中读取二维列表

[英]Read 2d list from txt file fast in python3

I need to write a program in python that reads a 2d list from a txt file and then does some stuff in certain elapsed time (ie 2 seconds).我需要在 python 中编写一个程序,它从 txt 文件中读取 2d 列表,然后在特定的经过时间(即 2 秒)内执行一些操作。

3 3
ULR
RRL
UUD

This is how the txt file is inside.这就是txt文件在里面的样子。

with open(argv[1]) as f:
n,m=f.read().split()
n=int(n)
m=int(m)
a=[[char for char in line]for line in f]  

And this is the code I use to parse the data into a 2d list.这是我用来将数据解析为二维列表的代码。
My issue is that its too slow.我的问题是它太慢了。 The main algorithm of the program has a time complexity of O(n^2) and I have written the same program in c to test the same inputs.该程序的主要算法的时间复杂度为 O(n^2),我在 c 中编写了相同的程序来测试相同的输入。 In order to successfully terminate with an 999x999 array as input, the c program takes about 5 seconds, while the python one takes a lot more than 10. Since the algorithm is effectively the same, my next thought is that my way of passing data from the file into a 2d list in python is to blame.为了以 999x999 数组作为输入成功终止,c 程序大约需要 5 秒,而 python 需要超过 10 秒。由于算法实际上是相同的,我的下一个想法是我从将文件放入 python 中的二维列表是罪魁祸首。
Appreciate your input:).感谢您的意见:)。

I think this might be faster:我认为这可能会更快:

with open("filename.txt", encoding="UTF-8") as ifile:
    m, n = ifile.readline().split()
    arr2d = list(map(list, ifile.readlines()))

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

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