在Python中按排序顺序从排序的迭代器中产生?

时间:2011-08-03 14:50:51

标签: python sorting iterator

有没有更好的方法将一堆已排序的迭代器合并/整理成一个,以便按排序顺序生成项目?我认为下面的代码可以工作,但我觉得有一种更清洁,更简洁的方法可以解决这个问题。

def sortIters(*iterables, **kwargs):
    key = kwargs.get('key', lambda x : x)
    nextElems = {}
    currentKey = None
    for g in iterables:
        try:
            nextElems[g] = g.next()
            k = key(nextElems[g])
            if currentKey is None or k < currentKey:
                currentKey = k
        except StopIteration:
            pass #iterator was empty
    while nextElems:
        minKey = None
        stoppedIters = set()
        for g, item in nextElems.iteritems():
            k = key(item)
            if k == currentKey:
                yield item
                try:
                    nextElems[g] = g.next()
                except StopIteration:
                    stoppedIters.add(g)
            minKey = k if minKey is None else min(k, minKey)
        currentKey = minKey
        for g in stoppedIters:
            del nextElems[g]

这个用例就是我有一堆csv文件,我需要根据一些排序字段进行合并。它们足够大,我不想只将它们全部读入列表并调用sort()。我正在使用python2.6,但如果有python3的解决方案,我仍然有兴趣看到它。

1 个答案:

答案 0 :(得分:25)

是的,你想要heapq.merge()完成一件事;按顺序迭代已排序的迭代器

def sortkey(row):
    return (row[5], row)

def unwrap(key):
    sortkey, row = key
    return row

from itertools import imap
FILE_LIST = map(file, ['foo.csv', 'bar.csv'])
input_iters = imap(sortkey, map(csv.csvreader, FILE_LIST))
output_iter = imap(unwrap, heapq.merge(*input_iters))