23-5 面试题:1000个员工,我们认为名字和年龄相等,就为同一个人

需求:
  • 一个类
  • 对象的属性 : 姓名 性别 年龄 部门
  • 员工管理系统
  • 内部转岗 python开发 - go开发
  • 姓名 性别 年龄 新的部门
  • alex None 83 python
  • alex None 85 luffy
  • 1000个员工
  • 如果几个员工对象的姓名和性别相同,这是一个人
  • 请对这1000个员工做去重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 = []   # 得到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'}


原文地址:https://www.cnblogs.com/zhuangdd/p/12637870.html