2016-07-21 53 views
-3

所以我做了一个代码,要求用户交换列表中的两个地方,直到列表从最小到最大。因此,它应该是这样的:有用户排序列表从最小到最大

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

请[编辑]让你的缩进是正确的。请使用空格而不是制表符。 –

+0

看起来不错,为什么不对'list'进行排序并将其设置为像'sorted_list'这样的变量,并继续执行您的操作,还要检查每个用户输入,直到列表等于'sorted_list'为止 – davedwards

+2

使用'list'作为变量标识符可能会产生误导。改用'lst','L','my_list'等。 – Tonechas

回答

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

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

(编辑:用户TesselatingHecker固定一个更好的模式verify_index功能,建议)

+0

一件小事就是允许'list'具有不同的长度,而不是对'1-10'范围进行硬编码并使用'len()'而不是 – mitoRibo

+0

@rbierman是的的确如此。也可以更改可能有冲突/误导性的列表变量标识符。谢谢 –

+0

第一个函数'verify_index'是'if(true)return true else else return'的反模式,可以直接返回1 <= number <= 10'。但是你可以摆脱它,并用'if 1 <= num1 <= 10'替换'如果verify_index(num1)',它将表现相同甚至更少的字符。 – TessellatingHeckler

相关问题