【问题标题】:Sort a list trough a function from user's input通过用户输入的函数对列表进行排序
【发布时间】:2026-02-23 19:55:02
【问题描述】:

我正在尝试编写一个函数,该函数将用户输入的整数列表作为参数并对其进行排序。

我遇到了一些问题,因为如果我将整数转换为字符串(我认为这可能是最好的方法,因为输入中有逗号)并将它们附加到一个空列表中,我会收到一个错误。

这里是函数:

def sort_integers(x):
    lst = []
    for i in x:
        lst.append(i)
        sorted_list = sorted(lst)
    print(sorted_list)
    
sort_integers(str(input("Enter some numbers: ")))

但如果我输入 10、9、8 作为整数,这就是我得到的输出:

[',', ',', '0', '1', '8', '9']

预期输出为:8,9,10。我曾尝试使用sort_integers(int(input("Enter some numbers: "))),但出现此错误:

ValueError: invalid literal for int() with base 10: '10,9,8'

我做错了什么?

【问题讨论】:

  • 你学习split了吗?如果没有,请这样做。谷歌“Python 拆分字符串”。您需要拆分输入字符串,然后将生成的字符串列表转换为数字列表。
  • 在循环中使用输入并将它们作为 int 附加到新列表中。然后 sort() 该列表..
  • @TechieViN 这并不能解决从一行中读取多个用逗号分隔的数字的问题。
  • 尝试sort_integers(map(int, input("...").split(','))),即split字符串由,,然后map每个子字符串到int

标签: python list input


【解决方案1】:

您只对digits 感兴趣,当您使用 for 循环时,您声明我的字符串中的每个符号将其添加到列表中,, (空格)是 Python 的符号。

在字符串上使用str.split() 会返回一个列表,其中包含字符串have a read on it 中的元素。 split() 接受您想要拆分字符串的参数,在您的情况下为 ,

要实现您的结果,您可以使用以下方法:

def sort_integers(x):
    return sorted([x for x in x.split(',') if x.isdigit()])

我正在返回排序列表,该列表是根据您传递给函数的字符串构建的,并且使用 str.isdigit() 内置方法仅获取数字。

此外,您不需要使用str(input(),因为input() 总是返回一个字符串,无论您传递什么。

【讨论】:

    【解决方案2】:

    试试这个:

    def sort_integers(x):
        x = x.split(',')
        sorted_list = sorted([int(i) for i in x])
        print(sorted_list)
    
    sort_integers(str(input("Enter some numbers: ")))
    

    或者这个(对现有代码的最小更改)

    def sort_integers(x):
        x = x.split(',')
        lst = []
        for i in x:
            lst.append(int(i))
            sorted_list = sorted(lst)
        print(sorted_list)
    
    
    sort_integers(str(input("Enter some numbers: ")))
    

    输出

     Enter some numbers: 10,9,8
     [8, 9, 10]
    

    【讨论】:

      【解决方案3】:

      所以我假设您的输入是:0,1,89

      当你一次遍历这个字符串时:

      x = "0,1,89"
      for i in x:
          print(i)
      

      你的输出将是

      0
      ,
      1
      ,
      8
      9
      

      当遍历一个字符串时,你一次只能得到一个字符。您的问题是您还将, 附加到列表中。

      第一个解决方案:

      def sort_integers(x):
          lst = []
          for i in x:
              if(i != ","):       # Only append to list of the character is not a comma
                  lst.append(i)
      
          sorted_list = sorted(lst)    # You shouldn't sort the list in a loop, only after you have everything in the list already
          print(sorted_list)
          
      sort_integers(str(input("Enter some numbers: ")))
      

      第二种解决方案:(推荐)

      def sort_integers(x):
          lst = []
          for i in x:
              try:
                  int(i)          # Try to convert the string to a number, 
                                  # if it works the code will go on 
                                  # otherwise it will be handled by except below
                  lst.append(i)
              except ValueError:
                  print("This is not a number so skipping")
      
          sorted_list = sorted(lst)    # You shouldn't sort the list in a loop, only after you have everything in the list already
          print(sorted_list)
          
      sort_integers(str(input("Enter some numbers: ")))
      

      【讨论】:

        最近更新 更多