优化Python过滤程序的技巧

2024-05-17 09:53:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在做一个非常简单的程序,其要点如下:

    post = open(INPUTFILE1, "rb")
    for line in post:
        cut = line.split(',')
        pre = open(INPUTFILE2, "rb")
        for otherline in pre:
            cuttwo = otherline.split(',')
            if cut[1] == cuttwo[1] and cut[3] == cuttwo[3] and cut[9] == cuttwo[9]:
                OUTPUTFILE.write(otherline)
                break
    post.close()
    pre.close()
    OUTPUTFILE.close()

实际上,这是将两个csv文件作为输入(“pre”和“post”)。它查看“post”数据中的第一行,并尝试在“pre”数据中找到与第2、4和10列匹配的行。如果存在匹配项,它会将“pre”数据写入新文件。你知道吗

它工作的很好,但它需要永远。尽管我的“post”数据可能只有几百行(最多可能有1000行),但我的“pre”数据可能多达1500万行。因此,可能需要大约10个小时才能完成。你知道吗

我对Python还比较陌生,所以在优化技术方面我还没有学到很多东西。有人对我可以尝试什么有什么建议吗?显然,我知道当我搜索整个“pre”数据寻找匹配项时,会发生logjam。有没有办法加快速度?你知道吗


Tags: and数据inforcloselineopenpost
1条回答
网友
1楼 · 发布于 2024-05-17 09:53:30

如果你只有几百行是潜在的,那么使用如下方法:

from operator import itemgetter
key = itemgetter(1, 3, 9)
with open('smallfile') as fin:
    valid = set(key(line.split(',')) for line in fin)

with open('largerfile') as fin:
    lines = (line.split(',') for line in fin)
    for line in lines:
        if key(line) in valid:
            # do something....

这节省了不必要的迭代,并充分利用了Python的内置功能以实现高效的查找。你知道吗

如果要在输出中使用小文件的整行(如果存在匹配项),请使用字典而不是集合:

from operator import itemgetter
key = itemgetter(1, 3, 9)
with open('smallfile') as fin:
    valid = dict((key(line.split(',')), line) for line in fin)

然后你的处理循环会是这样的:

with open('largerfile') as fin:
    lines = (line.split(',') for line in fin)
    for line in lines:
        otherline = valid.get(key(line), None)
        if otherline is not None:
            # do something....

相关问题 更多 >