基本的python类和大型if语句

如何解决基本的python类和大型if语句

尝试为作业做一些代码。希望我们以每小时最快的速度打印汽车品牌的名称。但是,为了找出最快的速度,老师希望我们做大量的if陈述来找出答案。

class carspeed:
    def __init__ (self,distance,time):
        self.distance=distance
        self.time=time
    
    def cspeed(self):
        return (self.distance)//(self.time)
        
Ford=carspeed(120,1.75)
Ferrari=carspeed(100,1.20)
BMW=carspeed(205,2.35)
Porsche=carspeed(155,1.85)
Audi=carspeed(190,2.10)
Jaguar=carspeed(255,2.45)

print("Ford speed in MPH:",Ford.cspeed())
print("Ferrari speed in MPH:",Ferrari.cspeed())
print("BMW speed in MPH:",BMW.cspeed())
print("Porsche speed in MPH:",Porsche.cspeed())
print("Audi speed in MPH:",Audi.cspeed())
print("Jaguar speed in MPH:",Jaguar.cspeed())

a=Ford.cspeed()
b=Ferrari.cspeed()
c=BMW.cspeed()
d=Porsche.cspeed()
e=Audi.cspeed()
f=Jaguar.cspeed()

def max_of_speed (a,b,c,d,e,f):
    fastest=a
    if fastest<b:
        fastest=b
    if fastest<c:
        fastest=c
    if fastest<d:
        fastest=d
    if fastest<e:
        fastest=e
    if fastest<f:
        fastest=f
    return fastest

print("The brand with the highest MPH is:",fastest)

#the(输出)

Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH is: 68.0

#期望的输出

Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH is: Jaguar

解决方法

不给变量起名字,而是向name添加新属性carspeed

class carspeed:
    def __init__ (self,name,distance,time):
        self.name = name
        self.distance=distance
        self.time=time
    
    def cars(self):
        return (self.distance)//(self.time)


c1=carspeed('Ford',120,1.75)
c2=carspeed('Ferrari',100,1.20)
c3=carspeed('BMW',205,2.35)

cars = [c1,c2,c3]
fastestCar = max(cars,key=lambda item: item.cars())  # use Python's max function the get the fastest car!
print(fastestCar)  # returns the instance!
print("The brand with the highest MPH is:",fastestCar.name)

出局:

<__main__.carspeed object at 0x1032e6c70>
The brand with the highest MPH is: BMW
,

您需要以某种方式保持与速度值相关联的品牌名称,以便以后打印。您已经有一个包含速度值的对象。为什么不向包含品牌名称的对象添加变量。然后,不要传递逻辑中的最终速度数字,而是传递每个品牌汽车的对象。

您可以在这里做更多的事情。代码的最大问题是,您不必将汽车的数量硬编码到代码中……也就是说,如果添加一辆汽车,所有代码都必须更改。您真正想要的是将您的汽车对象存储在列表或字典中,然后在该数据结构上进行迭代以进行处理,无论结构中有多少汽车,而无需关心有多少汽车。

这是您的代码的一个版本,可以解决所有这些问题,并为您提供所需的结果:

class car:
    def __init__(self,time):
        self.name = name
        self.distance = distance
        self.time = time

    def cspeed(self):
        return (self.distance) // (self.time)


cars = [
    car("Ford",1.75),car("Ferrari",1.20),car("BMW",2.35),car("Porsche",155,1.85),car("Audi",190,2.10),car("Jaguar",255,2.45)
    ]

for car in cars:
    print("%(name)s speed in MPH: %(speed)s" % {'name': car.name,'speed': car.cspeed()})

fastest = max(cars,key=lambda item: item.cspeed())

print("The brand with the highest MPH of %(speed)d is %(name)s"
        % { 'speed': fastest.cspeed(),'name': fastest.name})

结果:

Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH of 104 is Jaguar
,

您本可以以更好的方式完成此操作,但无需更改很多代码即可执行此操作,但请注意,这不是最佳的执行方式

class carspeed:
    def __init__ (self,time):
        self.distance=distance
        self.time=time
    
    def cspeed(self):
        return (self.distance)//(self.time)
        
Ford=carspeed(120,1.75)
Ferrari=carspeed(100,1.20)
BMW=carspeed(205,2.35)
Porsche=carspeed(155,1.85)
Audi=carspeed(190,2.10)
Jaguar=carspeed(255,2.45)

print("Ford speed in MPH:",Ford.cspeed())
print("Ferrari speed in MPH:",Ferrari.cspeed())
print("BMW speed in MPH:",BMW.cspeed())
print("Porsche speed in MPH:",Porsche.cspeed())
print("Audi speed in MPH:",Audi.cspeed())
print("Jaguar speed in MPH:",Jaguar.cspeed())

a=[Ford.cspeed(),'Ford']
b=[Ferrari.cspeed(),'Ferrari']
c=[BMW.cspeed(),'BMW']
d=[Porsche.cspeed(),'Porsche']
e=[Audi.cspeed(),'Audo']
f=[Jaguar.cspeed(),'Jaguar']

def max_of_speed (a,b,c,d,e,f):
    fastest = a[0]
    brand = a
    if fastest<b[0]:
        fastest=b[0]
        brand = b
    if fastest<c[0]:
        fastest=c[0]
        brand = c
    if fastest<d[0]:
        fastest=d[0]
        brand = d
    if fastest<e[0]:
        fastest=e[0]
        brand = e
    if fastest<f[0]:
        fastest=f[0]
        brand = f
    return brand[1]

print("The brand with the highest MPH is:",max_of_speed(a,f))
,

由于将所有车速放入一堆单独的变量中而不是某种集合中,因此您遇到了问题。我建议一本字典。这是您的代码的样子:

class Carspeed:
    def __init__ (self,time):
        self.distance=distance
        self.time=time
    
    def cspeed(self):
        return (self.distance)//(self.time)

# for shorter version of this function - see below
def max_of_speed(car_speeds):
    max_speed = None
    brand = None
    for name,value in car_speeds.items():
        speed = value.cspeed()
        if max_speed is None or speed > max_speed:
            brand = name
            max_speed = speed
    return brand

car_speeds = {
    'Ford': Carspeed(120,'Ferrari': Carspeed(100,'BMW': Carspeed(205,'Porsche': Carspeed(155,'Audi': Carspeed(190,'Jaguar': Carspeed(255,2.45),}

for name,value in car_speeds.items():
    print(f"{name} speed in MPH:",value.cspeed())

print("The brand with the highest MPH is:",max_of_speed(car_speeds))

打印输出:

Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH is: Jaguar

我已尝试避免在上面的代码中使用任何过于复杂的内容,但这是max_of_speed函数的单行版本,您可以根据需要使用它。

def max_of_speed(car_speeds):
    return max(car_speeds,key=lambda name:car_speeds[name].cspeed())
,

只需按照您的代码和说明的方式进行,添加以下作业即可满足您的期望。

Output

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res