python - 找到某个属性最高的实例
问题描述
这是一门汽车课。
我想找到最多的汽车cc
以及它brand
是什么。
class car:
category = 'auto'
def __init__(self,brand,color,cc):
self.brand = brand
self.color = color
self.cc = cc
def fastest(*args):
return max(args)
nissanCar = car("Nissan","red",1800)
MercendesCar = car("Mercendes","gold",1600)
LamborghiniCar = car("Lamborghini","green",3000)
print(f"The fastest car is {fastest(nissanCar.cc,MercendesCar.cc,LamborghiniCar.cc)} cc and the its brand is ")
这将返回:
The fastest car is 3000 cc and its brand is
如何知道那辆车的品牌是什么?
解决方案
我已经更新了您的代码,以便它可以显示多辆最快的汽车。最终可能会有大量的汽车,并且可能会有不止一辆具有相同 cc 的汽车。
如果您有任何问题,请在评论中告诉我。
欢迎来到堆栈溢出!
class car:
category = 'auto'
def __init__(self,brand,color,cc):
self.brand = brand
self.color = color
self.cc = cc
def fastest(cars):
max_cc = max([car.cc for car in cars])
fastest_cars = [car for car in cars if car.cc == max_cc]
return fastest_cars
NissanCar = car("Nissan","red",1800)
MercedesCar = car("Mercendes","gold",1600)
LamborghiniCar = car("Lamborghini","green",3000)
fastest_cars = fastest([NissanCar, MercedesCar, LamborghiniCar])
for fastest_car in fastest_cars:
print(f"The fastest car is {fastest_car.brand} with {fastest_car.cc} cc")
推荐阅读
- arduino - 树莓派 Smbus I2C 通信 Arduino throw Erro 121
- regex - 带有正则表达式匹配器的 groovy 脚本 - Stringvariable =~ '^(1.[/\\w]+)' 在 jenkins 版本 2.176.2 中无法正常工作
- sql-server - 将 Access 交叉表查询转换为 SQL Server
- python - 每次出现X时如何添加空格?
- jquery - 在eclipse中导入maven项目但运行时显示错误
- makefile - Makefile中的顶级逗号?
- javascript - 触发上下文菜单事件时停止按钮失去焦点
- javascript - 如何将具有属性的对象数组与另一个数组分组
- html - CSS如何将子菜单项保留在包装器中
- qt - 如何从组件 QTextDocument 获取没有元信息的 HTML 文本