当两个或多个查询集合并时,可以保持它们顺序的任何东西

2024-04-29 15:40:15 发布

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

我有两个不同的模型,我想把它们的查询集组合在一起。我知道我可以用itertools.chain公司将它们连接在一起,同时保留它们的迭代器特性

假设两个集合的顺序相同,我需要一个迭代器,您可以给出两个查询集和它们的排序字段,然后它将交错两个或多个集合,保留它们共享的顺序。查询集可能都非常大,所以我不想将它们作为列表处理。有人知道什么吗?你知道吗

早在DBMS出现之前,当我还是一个大型机Cobol程序员的时候,这种东西就是我的谋生之道。你知道吗


Tags: 模型chain列表排序顺序公司特性程序员
1条回答
网友
1楼 · 发布于 2024-04-29 15:40:15

这是我写的一个发生器,它可以进行交织。我还没有完全测试过它,但它似乎确实有效。你知道吗

def interleave(query1, query2, field=None, order='ASC'):

    iter1 = query1.iterator()
    iter2 = query2.iterator()

    next_1 = next(iter1, None)
    next_2 = next(iter2, None)

    while next_1 and next_2:
        if order == 'ASC':
            if getattr(next_1, field ) < getattr(next_2, field):
                yield next_1
                next_1 = next(iter1, None)
            else:
                yield next_2
                next_2 = next(iter2, None)
        else:
            if getattr(next_1, field ) >= getattr(next_2, field):
                yield next_1
                next_1 = next(iter1, None)
            else:
                yield next_2
                next_2 = next(iter2, None)

    if next_1:
        yield next_1
        while iter1:
            yield next(iter1)

    if next_2:
        yield next_2
        while iter2:
            yield next(iter2)

相关问题 更多 >