如何在Python中找到列表中的最小值或最大值

我是编程新手。假设我想使用 python 中的年龄列表来连续存储一个值,如果我发现某人是最年轻/最年长的,我想在屏幕上说出来。我尝试了这个,但似乎不起作用,有人可以告诉我出了什么问题并帮助我吗?


ageslst= []

while True:

    age = int(input('age?'))

    ageslst.append(agelst)        

    if age > max(ages):

            print('Oldest')    

     if age < min (agelst):

            print(' Youngest')


慕哥9229398
浏览 58回答 2
2回答

慕丝7291255

这将完成您想要做的事情:ageslst= []while True:&nbsp; &nbsp; age = int(input('age?'))&nbsp; &nbsp; ageslst.append(age)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if age == max(ageslst):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if age == min(ageslst):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Youngest')我修复了第二条语句的缩进if,调整了变量以实际在应该使用的地方使用,并且我还更改了测试条件 from>和<to ==(测试相等性 -=是赋值运算符)。如果用户输入迄今为止最大的年龄,它就会被添加到其中,ageslst并且现在是那里的最大值。因此,测试if age > max(ageslst)永远不会是真实的。最后,您可能应该向循环添加某种终止条件,否则它将永远运行。

繁花如伊

这里有几个问题:ageslst.append(age)if age > max(ages):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;if age < min (ages):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')每个新年龄都存储在age变量中,并且ageslst是您累积的所有年龄的列表。您想要做的是将新时代与所有先前时代的列表进行比较。接下来,如果您age在检查之前附加到列表,那么您的if条件将永远不会是True,因为新年龄总是已经在列表中。重新设计它以解决这些问题:if age > max(ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;elif age < min (ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')ageslst.append(age)检查年龄是否超过列表中的最大年龄否则,检查年龄是否小于列表中的最小年龄最后,将年龄附加到列表中这里有几个问题:ageslst.append(age)if age > max(ages):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;if age < min (ages):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')每个新年龄都存储在age变量中,并且ageslst是您累积的所有年龄的列表。您想要做的是将新时代与所有先前时代的列表进行比较。接下来,如果您age在检查之前附加到列表,那么您的if条件将永远不会是True,因为新年龄总是已经在列表中。重新设计它以解决这些问题:if age > max(ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;elif age < min (ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')ageslst.append(age)检查年龄是否超过列表中的最大年龄否则,检查年龄是否小于列表中的最小年龄最后,将年龄附加到列表中这里有几个问题:ageslst.append(age)if age > max(ages):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;if age < min (ages):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')每个新年龄都存储在age变量中,并且ageslst是您累积的所有年龄的列表。您想要做的是将新时代与所有先前时代的列表进行比较。接下来,如果您age在检查之前附加到列表,那么您的if条件将永远不会是True,因为新年龄总是已经在列表中。重新设计它以解决这些问题:if age > max(ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print('Oldest')&nbsp; &nbsp;&nbsp;elif age < min (ageslst):&nbsp; &nbsp; &nbsp; &nbsp; print(' Youngest')ageslst.append(age)检查年龄是否超过列表中的最大年龄否则,检查年龄是否小于列表中的最小年龄最后,将年龄附加到列表中
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python