用到知识
1、面向对象
2、内置函数__hash__
3、内置函数__eq__
一、试题简介
1、定义一个类,然后类中对象的属性有:姓名,性别,年龄,部门
2、假设几年后,内部员工转岗了,
3、到了另一个岗位后,姓名,性别,年龄新的部门,在另一个员工表有了新的数据
4、然后我认定,假设员工对象的姓名和性别一致,那么我就认定这是一个人
5、去重,筛选
1、说到去重,首先想到 set集合
2、然后,与 set 有关的内置函数 __hash__,__eq__
3、hash算法,我自定义了hash的方法,让他只计算员工的 name 和 sex,如果 hash 的值相同
4、那么就执行 __eq__ 这个函数,然后判断它们的 name and sex 是否相同
5、相同就去重。
6、最后打印出来,测试结果
class Employee:
def __init__(self,name,age,sex,partment):
self.name = name
self.age = age
self.sex = sex
self.partment = partment
def __hash__(self):
'''判断 hash 值是否相等'''
return hash('%s %s' %(self.name,self.sex))
def __eq__(self,other):
'''如果 hash 相等的话,然后就会触发 __eq__方法
来判断他们的 name 和 sex 是否相等,然后再来去重'''
if self.name == other.name and self.sex == other.sex:
return True
employee_list = []
for i in range(200):
'''假设创建了两百个员工,但是年龄不同'''
employee_list.append(Employee('mayun',i,'man','entrepreneur'))
for i in range(200):
employee_list.append(Employee('mahuateng',i,'man','entrepreneur'))
for i in range(200):
employee_list.append(Employee('liuqiangdong',i,'man','entrepreneur'))
# print(employee_list)
employee_list = set(employee_list)
for person in employee_list:
print(person.__dict__)
#使用 set 后先触发 hash 判断,如果hash相等的话,这时候就会触发__eq__
340

被折叠的 条评论
为什么被折叠?



