Skip to main content
 首页 » 编程设计

python之python中的归并排序

2025年05月04日12think

基本上我有一堆包含域的文件。我使用 .sort(key=func_that_returns_tld) 根据其 TLD 对每个文件进行了排序

既然我已经完成了,我想合并所有文件并最终得到一个巨大的排序文件。我想我需要这样的东西:

open all files 
read one line from each file into a list 
sort list with .sort(key=func_that_returns_tld) 
output that list to file 
loop by reading next line 

我在想这个对吗?任何关于如何实现这一点的建议将不胜感激。

请您参考如下方法:

如果您的文件不是很大,那么只需将它们全部读入内存(如 S. Lott 建议的那样)。那绝对是最简单的。

但是,您提到整理会创建一个“大”文件。如果它太大而无法放入内存,那么也许使用 heapq.merge .设置起来可能有点困难,但它的优点是不需要一次将所有可迭代对象拉入内存。

import heapq 
import contextlib 
 
class Domain(object): 
    def __init__(self,domain): 
        self.domain=domain 
    @property 
    def tld(self): 
        # Put your function for calculating TLD here 
        return self.domain.split('.',1)[0] 
    def __lt__(self,other): 
        return self.tld<=other.tld 
    def __str__(self): 
        return self.domain 
 
class DomFile(file): 
    def next(self): 
        return Domain(file.next(self).strip()) 
 
filenames=('data1.txt','data2.txt') 
with contextlib.nested(*(DomFile(filename,'r') for filename in filenames)) as fhs: 
    for elt in heapq.merge(*fhs): 
        print(elt) 

使用 data1.txt:

google.com 
stackoverflow.com 
yahoo.com 

和data2.txt:

standards.freedesktop.org 
www.imagemagick.org 

产量:

google.com 
stackoverflow.com 
standards.freedesktop.org 
www.imagemagick.org 
yahoo.com