python - 对象上的 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)
解决方案
为此,您可以使用参数使用标准min
函数key
:
youngest = min(employees, key=lambda x:x.age)
推荐阅读
- python-3.x - Convert date with string component to date time format in python
- php - 如何修复 PHP 错误:“调用未定义函数 posix_strerror()”
- python-3.x - boto3.client 和 pymysql.connect 的区别
- go - GoLand 没有检测到 $GOPATH/pkg/mod 下的供应商包?
- laravel - 如何根据同一行的ID设置列的值?
- jupyter-notebook - 启动 Jupyter Notebook 时出错 - @attr.s(hash=True) AttributeError: module 'attr' has no attribute 's'
- python - 如何在 pyqtgraph 的 mplwidget 中绘制 X 轴上的日期
- python - Rasa 网络聊天集成问题
- conv-neural-network - 如何在实现自己的池化层时处理由于输入形状(如 (None, 1024, 1024, 4))而导致的“TypeError”?
- c - 为什么输入奇数时这个循环不起作用?