需求:
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 = [] # 得到600个样本 for i in range(200): employ_lst.append(Employee(‘alex‘, i, ‘male‘, ‘python‘)) # 这样得到了 年龄不同,名字都为alex的对象们 放入空列表中待用 for i in range(200): employ_lst.append(Employee(‘wusir‘, i, ‘male‘, ‘python‘)) # 这样得到了 年龄不同名字都为wusir的对象们 放入空列表中待用 for i in range(200): employ_lst.append(Employee(‘taibai‘, i, ‘male‘, ‘python‘)) # print(employ_lst) employ_set = set(employ_lst) # set 去重 for person in employ_set: print(person.__dict__) # 查看对象们
# 结果:
# {‘name‘: ‘alex‘, ‘age‘: 0, ‘sex‘: ‘male‘, ‘partment‘: ‘python‘}
# {‘name‘: ‘taibai‘, ‘age‘: 0, ‘sex‘: ‘male‘, ‘partment‘: ‘python‘}
# {‘name‘: ‘wusir‘, ‘age‘: 0, ‘sex‘: ‘male‘, ‘partment‘: ‘python‘}
23-5 面试题:1000个员工,我们认为名字和年龄相等,就为同一个人
原文:https://www.cnblogs.com/zhuangdd/p/12637870.html