我制作了一个程序来计算列表中的第二大数字。输入是一个被切分到列表中的字符串。这是密码
score1 = input()
score = score1.split()
score.sort()
maximum = max(score)
count = score.count(maximum)
for i in range(0,count):
score.pop()
print(max(score))
对于正数,它可以正常工作,但如果列表中包含负数,我的程序将无法生成正确的答案
For Input
-7 -7 -7 -7 -6
Output is
-6
instead of-7
有什么办法可以改进吗
您的代码不适用于负数(顺便说一句,它也不适用于超过1位的数字)的原因是您没有对数字进行排序,而是对字符串进行排序
input()
的返回值始终是字符串,因为不会发生隐式转换。因此,为了得到你想要的结果,你必须先将它们转换成某种数字形式在那之后,你可以用它做任何你想做的事
请注意,将列表理解包装在
try-except
块中也是避免错误输入的好方法因为输入是一个字符串,所以当您调用
sort
和max
时,它们是按字典顺序工作的,而不是按数字工作的。您需要首先转换为整数:相关问题 更多 >
编程相关推荐