python - Python - 列表追加变慢?
问题描述
我的 Python 代码有问题。我正在处理一个包含分数的大 (3.5gb) JSON 文件,我需要它以 21984 个分数的块(这是一个查询的所有分数)。代码工作正常,但我的测试集是 4000 个查询。前 10 个速度很快,但之后它以指数方式增加了计算这部分代码的时间。所以 5 小时后,我有 500 个查询。这些打印是用于记录的,似乎问题在于将行翻译或附加到列表中。有谁知道如何使它更快或看到是什么导致它变慢?
def getscorebatch(number):
print('Creating Batch..')
batch_temp = list()
with open(json_file_name, 'r') as FileObj:
print("Creating slice...")
lines_gen = islice(FileObj, (21894 * number), ((21894 * number) + 21894))
print("Appending slice...")
for line in lines_gen:
line = line.translate({ord(c): None for c in ':",}{ \n'})
batch_temp.append(line)
return batch_temp
更新:我尝试实施您的建议,而且速度更快!太感谢了。我对生成器相当陌生,所以我现在不明白的是,如何获得正确的代码块?这每次都会给我第一块..
def generator(file_to_read):
c = 0
while c < 21894:
data = file_to_read.readline()
c += 1
if not data:
break
yield data
def getscorebatch(number):
print('Creating Batch..')
batch_temp = [0]*22000
with open(json_file_name, 'r') as FileObj:
gen_file = generator(FileObj)
batch_temp = [line.translate(line.maketrans("", "", REMOVE)) for line in gen_file]
print(len(batch_temp))
return batch_temp
解决方案
推荐阅读
- java - 无法在 WildFly 11 上上传部署
- java - onRequestPermissionsResult 中的 java.lang.StackOverflowError (Android)
- vue.js - vue-router 与参数链接(刷新时出错?)
- generics - 如何在 kotlin 中初始化动态嵌套对象?
- python - Python函数返回不正确的数据
- reactjs - redux 形式的谷歌地图
- jquery - jQuery 验证。验证数组数组
- python - Python:基于 id 和时间范围的对象组列表
- xslt - BizTalk - 如何以编程方式调用 Visual Studio 验证映射并保存 XSLT
- scala - 为什么在 Scala 中这条语句不是 NullPointerException?null.asInstanceOf[双]