1. 程式人生 > >set集合去重機制

set集合去重機制

brush The pri light 相同 __init__ for turn ini

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集合去重機制