【问题标题】:Slow pairwise comparison慢成对比较
【发布时间】:2017-06-09 18:13:37
【问题描述】:

我有一个代码可以打开两个文件,将它们的内容保存到集合(set1 和 set2),并将这些集合之间的成对比较结果保存到输出文件。这两个文件都非常大(每个文件超过 100K 行),并且这段代码需要很长时间才能输出(超过 10 小时)。

有没有办法优化它的性能?

def matches2smiles():
    with open('file1.txt') as f:
    set1 = {a.rstrip('\n') for a in f}

    with open('file2.txt') as g:
        set2 = {b.replace('\n', '') for b in g}

    with open('output.txt', 'w') as h: 
        r = [                                                                    
            h.write(b + '\n')
            for a in set1
            for b in set2
            if a in b
            ]

matches2smiles()

【问题讨论】:

    标签: performance list set set-comprehension


    【解决方案1】:

    首先你的代码是假的,应该是:

        r = [                                                                    
            h.write(a + '\n')
            for a in set1
            if a in set2
            ]
    

    无论如何,使用set1.intersection(set2) - 它可能会更快更清晰的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多