将带有负数的列表排序为字符串会产生意外结果

2024-09-27 01:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个程序来计算列表中的第二大数字。输入是一个被切分到列表中的字符串。这是密码

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

有什么办法可以改进吗


Tags: 字符串in程序密码列表forinputcount
3条回答
score1 = input()
score = score1.split()

#converting the list of strings into list of integers
score = [int(i) for i in score]

#removing duplicates
score = list(set(score))

#sorting the list
score.sort()

#printing the second largest number

print(score[-2])

您的代码不适用于负数(顺便说一句,它也不适用于超过1位的数字)的原因是您没有对数字进行排序,而是对字符串进行排序input()的返回值始终是字符串,因为不会发生隐式转换。因此,为了得到你想要的结果,你必须先将它们转换成某种数字形式

score = [int(x) for x in input().split()]
score.sort()

在那之后,你可以用它做任何你想做的事

请注意,将列表理解包装在try-except块中也是避免错误输入的好方法

因为输入是一个字符串,所以当您调用sortmax时,它们是按字典顺序工作的,而不是按数字工作的。您需要首先转换为整数:

score = [int(item) for item in score1.split()]

相关问题 更多 >

    热门问题