首页 > 解决方案 > 找到某个属性最高的实例

问题描述

这是一门汽车课。

我想找到最多的汽车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

如何知道那辆车的品牌是什么?

标签: pythonoop

解决方案


我已经更新了您的代码,以便它可以显示多辆最快的汽车。最终可能会有大量的汽车,并且可能会有不止一辆具有相同 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")

推荐阅读