将用户排序列表从最小到最大

时间:2016-07-21 23:54:39

标签: python python-3.x

所以我正在编写一个代码,要求用户交换列表中的两个位置,直到列表从最小到最大。所以看起来应该是这样的:

Hello:  Your current list is [6, 7, 8, 2 , 9, 10, 12, 15, 16, 17]
Please pick your first location ->   4
Please pick your second location ->  2
Your new list is [6, 2, 8, 7 , 9, 10, 12, 15, 16, 17]

我已经完成了这一部分,但我目前无法弄清楚如何让用户进行排序而不是代码。

Your list is not sorted: Please continue
Please pick your first location ->   1
Please pick your second location ->  2

Your new list is [2, 6, 8, 7 , 9, 10, 12, 15, 16, 17]
Please pick your first location ->   3
Please pick your second location ->  4

Your new list is [2, 6, 7, 8 , 9, 10, 12, 15, 16, 17]

Great job, thank you for sorting my list.

这是我的代码:

list = [4,2,5,5,6,4,7,6,9,5]
print("Heres your current list", list)

print("Pick a location between 1 and 10")
num = int(input())
if num <= 10 and num >= 1:
    print("Please pick another location between 1 and 10")
    num1 = int(input())
    tempBox1 = list[num-1]
    tempBox2 = list[num1-1]
    list[num-1] = tempBox2
    list[num1-1] = tempBox1
    print("Your new list is", list)

1 个答案:

答案 0 :(得分:1)

从我可以理解的有些令人困惑的解释中,我使用一些良好的编码行为制作了这个工作脚本,每个初学者都应该在开始python和编程时学习。这两个第一个小函数用于避免代码重复,这样我就可以避免使用所有代码的主函数太长。

此外,最后一个条件是在运行任何python脚本时发生的事情(您可以找到关于here的更好解释)。

# Function to avoid code repetition
def verify_index(number):
    return 1 <= number <= 10

# Function to ask for the number indexes until they fit the list length
def input_numbers():
    while True:
        num1 = int(input("Pick a location between 1 and 10: "))
        num2 = int(input("Please pick another location between 1 and 10: "))
        if verify_index(num1) and verify_index(num2):
            return num1, num2

# List and variables defined locally here
def main_function():
    list = [2, 4, 5, 5, 5, 5, 5, 5, 9, 5]
    print("Heres your current list", list)
    num1, num2 = input_numbers()
    while True:
        print(num1,num2)
        temp = list[num1-1]
        list[num1-1] = list[num2-1]
        list[num2-1] = temp
        print("Your new list is now: ", list)
        if list == sorted(list):
            break
        num1, num2 = input_numbers()
    print("Congratulations! Your list is now sorted by your commands!")

# Code your script will execute once is run
if __name__ == '__main__':
    main_function()

如有任何问题或疑问,请随时提出。

(编辑:修复verify_index函数以获得更好的模式,用户TesselatingHecker的建议)