Python使用set()对对象进行去重解决思路

问题背景:

ORM查询出来多个对象列表,例如

list1 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list1))

list2 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list2))

list3 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list3))

list4 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list4))

需求:

需要对多个对象列表里面的对象进行去重求交并集。

上来就这样?

直接使用

real_obj_list = list(set(list1).union(list2, list3, list4))  # 求多个list的并集

直接报错:Adgroup类对象不是可hash的!!!

重点来了!!!

注:set 对类对象去重,在于重写__eq__方法和__hash__方法,如果没有重写__hash__会导致Adgroup类对象不是可hash的

class Adgroup(object):
    def __init__(self, title, price):
        self.title= title
        self.price= price
        
    def __eq__(self, other):
        if isinstance(other, Adgroup):
        	# title和price相同就认为对象相同
            return ((self.title== other.title) and (self.price== other.price))  
        else:
            return False
            
    def __ne__(self, other):
        return (not self.__eq__(other))
        
    def __hash__(self):
    	# title和price相同就认为对象相同
        return hash(self.title) + hash(self.price)

然后就可以使用set()对对象列表的对象进行去重啦!!!

发布了146 篇原创文章 · 获赞 66 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_38923792/article/details/103605489