首页 > 解决方案 > 对象上的 Python reduce 函数

问题描述

我正在尝试编写一个函数,该函数接受员工对象列表并返回与年龄最小的员工对应的对象。我不确定它为什么会破裂。我知道有很多方法可以做到这一点,但我对通过 reduce 工具解决它特别感兴趣

from functools import reduce as r
class Employee:
    bonus = 0
    def __init__(self,firstname,lastname,age,salary):
        self.fullname = firstname + " "+ lastnamestname
        self.email = "{}{}@outlook.com".format(firstname,lastname)
        self.age = age
        self.compensation = salary + self.bonus

e1 = Employee("Adam","George",33,100)
e2 = Employee("Samuel","Steans",35,133)
e3 = Employee("Laura","Nobel",25,200)
e4 = Employee("David","Chan",21,100)
e5 = Employee("Ben","Smith",80,90)
e6 = Employee("Santa","Ergory",19,120)
e7 = Employee("Tim","Smith",18,150)
e8 = Employee("Paul","Goodfellow",50,180)

employees = [e1,e2,e3,e4,e5,e6,e7,e8]

def getyoungest(emps):
    return r(lambda x,y:x.fullname if x.age < y.age else y.fullname,emps )

youngest = getyoungest(employees)
print(youngest)

标签: pythonreduce

解决方案


为此,您可以使用参数使用标准min函数key

youngest = min(employees, key=lambda x:x.age)

推荐阅读