通过用户输入的功能对列表进行排序

时间:2020-09-17 09:45:37

标签: python list input

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

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

此功能:

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'

我在做什么错了?

3 个答案:

答案 0 :(得分: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()始终返回字符串,无论传递给它什么。

答案 1 :(得分:1)

尝试一下:

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]

答案 2 :(得分:0)

所以我假设您输入的是: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: ")))
相关问题