为了账号安全,请及时绑定邮箱和手机立即绑定

python:如何找到其中最大数字的行?

python:如何找到其中最大数字的行?

月关宝盒 2021-06-14 15:04:38
如何在包含字符串和数字的行文件中找到最大数字的行def topSpeed(cars): y = raw_input("car type:")with open("cars","r") as f:    for l in f.readlines():        list = []        p = l.strip().split("|")        type = p[1]        max_speed = p[7]        if y == type:            list.append(l)            a = 0            for i in list:                p = i.strip().split("|")                max_speed = p[7]                                    if max_speed > a:                    a = max_speed                    print(i)                    pass                 else:                    print("...")            else:            print("no cars of that type")我试过了,但它打印了所有输入类型的汽车和汽车清单是:a1|bmw|a|3.5|2.6|1.6|2018|150|3|5|xa2|audi|a|2.50|1.60|4.50|2017|220|3|2|ya3|audi|b|2.30|1.80|5.00|2011|180|4|4|xa4|bmw|b|duz|vis|sir|god|230|3|5|y
查看完整描述

2 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

你的问题是循环:


for i in list:

    p = i.strip().split("|")

    max_speed = p[7]                    

    if max_speed > a:

        a = max_speed

        print(i)

         pass 

    else:

        print("...")

这将在每次 max_speed > a 时打印出“i”,因此如果您的最大速度按升序排列,它将打印出每辆车。您需要做的是以最大速度保存汽车,然后在最后打印出来。


max_speed_car = ''

for i in list:

    p = i.strip().split("|")

    max_speed = p[7]                    

    if max_speed > a:

        a = max_speed

        max_speed_car = i

        pass 

    else:

        print("...")

print(max_speed_car)

应该这样做。这是在我的计算机上运行良好的完整代码:(我正在运行 python 3.6)


def topSpeed(cars):

    y = input("car type:")

    with open(r"\cars.txt","r") as f:

            for l in f.readlines():

        list = []

        p = l.strip().split("|")

        type = p[1]

        max_speed = p[7]

        if y == type:

            list.append(l)

    a = 0

    max_speed_car = ''

    for i in list:

        p = i.strip().split("|")

        max_speed = int(p[7])                    

        if (max_speed > a):

            a = max_speed

            max_speed_car = i


        else:

            print("...")


    print(max_speed_car)


查看完整回答
反对 回复 2021-06-16
  • 2 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号