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()对对象列表的对象进行去重啦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值