码迷,mamicode.com
首页 > 其他好文 > 详细

set集合去重机制

时间:2018-08-06 20:13:58      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:%s   return   other   int   集合   end   dict   ret   iba   

set集合去重机制:先调用hash,若发现hash出的内存地址已被占用,会再次调用eq比较内容是否相同.

__hash__对与同一个值的同一次运算的结果是相同的

class Employee:
    def __init__(self,name,age,sex,partment):
        self.name = name
        self.age = age
        self.sex = sex
        self.partment = partment
    def __hash__(self):
        return hash(‘%s%s‘%(self.name,self.sex))
    def __eq__(self, other):
        if self.name == other.name and self.sex == other.sex:
            return True
employ_lst = []
for i in range(200):
    employ_lst.append(Employee(‘alex‘,i,‘male‘,‘python‘))
for i in range(200):
    employ_lst.append(Employee(‘wusir‘,i,‘male‘,‘python‘))
for i in range(200):
    employ_lst.append(Employee(‘taibai‘, i, ‘male‘, ‘python‘))

# print(employ_lst)
employ_set = set(employ_lst)
for person in employ_set:
    print(person.__dict__)

  

set集合去重机制

标签:%s   return   other   int   集合   end   dict   ret   iba   

原文地址:https://www.cnblogs.com/wszxdzd/p/9432261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!