比较不同类的两个列表并基于属性删除

2024-06-28 11:32:35 发布

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

我正在寻找一种有效的方法来比较两个类的列表。你知道吗

我有两类发票和事件。 我有事件发票id那就是引用发票id. 两个列表都有3万行。你知道吗

我要做的是删除在事件列表中找不到相关事件的发票。你知道吗

这是我的代码,但它真的很慢,有没有办法做得更快?你知道吗

for invoice in invoices:
        found = [tEv for tEv in pEvents if docExistsInEvents(invoice,tEv)]
        if not found:
            invoices.remove(invoice)

def docExistsInEvents(pInvoice, pEvent):
    if pInvoice.id == pEvent.invoice_id:
        return True

谢谢


Tags: 方法inid列表forif事件发票
1条回答
网友
1楼 · 发布于 2024-06-28 11:32:35

使用set

# assuming `invoices` contains all invoices and `events` all events

# build a set containing all relevant ids
event_invoice_ids = {event.invoice_id for event in events}

# create a list with only the relevant data by filtering invoices
# on the pre-built set of invoice ids
relevant_invoices = [invoice for invoice in invoices if invoice.id
                     in event_invoice_ids]

因为搜索是通过invoice id的散列来完成的,所以速度会快得多。你知道吗

相关问题 更多 >