2016-11-14 20 views
-3

我想獲取列表長度和相應的元素作爲輸入。獲取列表長度及其元素作爲輸入

 int(input("Please enter how long the list is: ")) 
     my_list = [56,3,89,2,34,12] 
    def my_sort(l) : 
my_sorted = False 
sorted_pos= len(l)-1 


print(l) 
while not sorted_list: 
    sorted_list= True 
    for index in range(sorted_pos): 
     if my_list[index] > my_list[index +1]: 
      sorted_list= False 
      my_list[index], my_list[index +1] = my_list[index +1], my_list[index] 
      print(l) 
+0

那麼,有什麼問題? – Mureinik

+1

你可以看到[獲取用戶輸入的數字列表](http://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user)。 – amin

回答

0

你可能想要這個:

elems = int(input("Please enter how long the list is: ")) 
my_list = [] 

for i in range(elems): 
    elem = int(input("Please enter next element: ")) 
    my_list.append(elem) 

def my_sort(l): 
    sorted_list = False 
    sorted_pos= len(l)-1 

    print(l) 

    while not sorted_list: 
     sorted_list = True 
     for index in range(sorted_pos): 
      if l[index] > l[index +1]: 
       sorted_list = False 
       l[index], l[index +1] = l[index +1], l[index] 
    print(l) 

my_sort(my_list) 

注意的是Python的縮進是非常重要的。

在第一條語句中,您將獲取用戶的項目數並將其保存在變量elems中。

然後在for循環中,您要求用戶放置單個元素並將其追加到(最初爲空)列表my_list

在下一步中,您將創建(定義)函數my_sort,該函數將參數作爲數字列表。您將此參數命名爲l。這個函數打印給定的列表,對它進行排序,最後打印排序列表。

最後一步是用名單my_list調用此函數,而不是正式參數l