在Python中对整数列表进行排序

bvd*_*orn 0 python sorting

我是一名初学者程序员,正在尝试练习。我想对整数列表进行排序,但是每次我运行代码时,列表都不会排序。我用sorted()或.sort()以几种不同的方式尝试过,但是似乎没有任何帮助。

def main():

    _list1_ = []
    _list2_ = []

    print("Enter random numbers and enter Q to quit: ")
    userInput1 = input("")
    while userInput1.upper() != "Q":
        _list1_.append(int(userInput1))
        userInput1 = input("")

    print("Enter random numbers and enter Q to quit:")
    userInput2 = input("")
    while userInput2.upper() != "Q":
        _list2_.append(int(userInput2))
        userInput2 = input("")

    sorted(_list1_)
    sorted(_list2_)

    print(_list1_)

main()
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 5

sorted()没有将列表排序。它返回排序后的列表,因此您需要将2个sorted()调用更改为以下内容:

_list1_ = sorted(_list1_)
_list2_ = sorted(_list2_)
Run Code Online (Sandbox Code Playgroud)

阅读文档以了解功能的工作原理总是一个好主意。这是用于排序的https://docs.python.org/2/library/functions.html#sorted的文档

  • _list_1.sort()和_list2_.sort()会就位。值得一提的是。 (4认同)