Python:比较2个实例列表 [英] python: comparing 2 lists of instances

查看:88
本文介绍了Python:比较2个实例列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实例列表:

list1
list2

每个实例都包含id,name等变量...

each instance contains variables such as id, name, etc...

我正在遍历list2,我想查找list1中不存在的条目.

I am iterating through list2, and I want to find entries that don't exist in list1.

例如.

for entry in list2:
  if entry.id in list1:
    <do something> 

我希望找到一种方法,而无需使用for循环.有简单的方法吗?

I'm hoping to find a way to do this without a douple for loop. Is there an easy way?

推荐答案

我可能会做类似的事情:

I might do something like:

set1 = set((x.id,x.name,...) for x in list1)
difference = [ x for x in list2 if (x.id,x.name,...) not in set1 ]

其中...是实例的其他(可哈希)服装-您需要包括足够多的服装才能使其唯一.

where ... is additional (hashable) attibutes of the instance -- You need to include enough of them to make it unique.

这将采用O(N * M)算法并将其转换为O(max(N,M))算法.

This takes your O(N*M) algorithm and turns it into an O(max(N,M)) algorithm.

这篇关于Python:比较2个实例列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆