【问题标题】:Sorting a list with negative numbers as strings produces unexpected result [duplicate]将带有负数的列表作为字符串排序会产生意外结果[重复]
【发布时间】:2020-10-19 16:25:41
【问题描述】:

我编写了一个程序来计算列表中的第二大数字。输入是一个被分割成列表的字符串。这是代码

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))

它对正数工作正常,但如果列表包含负数,我的程序无法产生正确的答案。

供输入 -7 -7 -7 -7 -6

输出是-6而不是-7

有什么办法改进吗?

【问题讨论】:

  • 您的数字被评估为字符串,而不是数字。提示:list(map(int, score1.split()))...
  • 在你的例子中输出不应该是-7吗?
  • 非常相似,可能是重复的? Python sorting list with negative number

标签: python list sorting


【解决方案1】:

由于输入是字符串,当您调用sortmax 时,它们按字典顺序工作,而不是按数字顺序工作。您需要先转换为整数:

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

【讨论】:

    【解决方案2】:

    不妨试试这个:

    score1 = input()
    score = score1.split()
    score = sorted(set(map(int, score)))
    second_max=score[-2]
    

    【讨论】:

    • 为什么会调用setlist? 1) 你不需要它们,2) 使用 set 删除重复项,这在这种情况下可能是一个错误。
    • 这超出了预期 OP 可能想要对列表执行的操作。删除所有出现的最大元素是一回事;假设所有重复项也应该被删除是另一回事。
    • 好吧,如果我没有误解 OP,他想从他的输入中获得第二大不同的数字吗?
    【解决方案3】:

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

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

    之后你就可以随心所欲了。

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

    【讨论】:

      【解决方案4】:
      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])
      

      【讨论】:

      • 短:score = sorted(set(score))
      【解决方案5】:

      您可以通过这样做得到预期的答案:

      score = input().split()
      li = []
      
      for value in score:
          x = int(value) # converting to int
          li.append(x) # appending to empty list
      final = set(li) # removing duplicates values
      print(max(final)) # getting the maximum value
      

      希望对你有所帮助..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-12
        • 2013-06-18
        • 1970-01-01
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        相关资源
        最近更新 更多