首页 > 解决方案 > 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

标签: pythonjsonpython-3.xlistappend

解决方案


推荐阅读