2017-10-05 30 views
1
def selection(alist): 
    sorted_list = [] 
    while alist: 
     minimum = alist.pop(alist.index(min(alist))) 
     sorted_list.append(minimum) 
    print(sorted_list) 
    return sorted_list 

a = [54,35,23,86,3546,87,43,7,2] 
selection(a) 
print(selection(a)) 
+0

您是否可以更新縮進以匹配正在執行的內容?很難判斷它是否輸入錯誤,或者縮進是否是其中的一部分問題。 – ryachza

+0

因爲你正在調用你的函數兩次,到第二次調用時,'a'已經是空的。爲每個函數調用創建一個'a'副本,或者只調用一次'section'。 –

+2

你正在改變列表順序'彈出'最小元素。這是令人難以置信的**效率低下,但順便說一句,它不完全清楚你正在描述什麼問題,但絕對,第二次你調用'選擇(一)'不會工作,因爲'a'將是一個空名單。 –

回答

0

嘗試將函數調用分配給變量。這將允許您存儲數據並在需要時調用它。

def selection(alist): 
    sorted_list = [] 
    while alist: 
     minimum = alist.pop(alist.index(min(alist))) 
     sorted_list.append(minimum) 
    print(sorted_list) 
    return sorted_list 

a = [54,35,23,86,3546,87,43,7,2] 
value = selection(a) 
print(value) 
0

它發生,因爲selection突然跳出的a所有的值。如果你想保持a原樣,你應該將其克隆到一個臨時數組,並且只能操作這個數組。

def selection(alist): 
    temp = list(alist) 
    sorted_list = [] 
    while temp: 
     minimum = temp.pop(temp.index(min(temp))) 
     sorted_list.append(minimum) 
    return sorted_list 

然後a保持不變:

>>> selection(a) 
[2, 7, 23, 35, 43, 54, 86, 87, 3546] 
>>> print(selection(a)) 
[2, 7, 23, 35, 43, 54, 86, 87, 3546] 
>>> a 
[54, 35, 23, 86, 3546, 87, 43, 7, 2] 

如果你的目標只是排序這個數組,你不關心不寫由yourslef排序算法,它很可能是一個更好的理念(和更有效)使用Python的內置sorted功能:

>>> a = [54,35,23,86,3546,87,43,7,2] 
>>> sorted(a) 
[2, 7, 23, 35, 43, 54, 86, 87, 3546] 
>>> a 
[54, 35, 23, 86, 3546, 87, 43, 7, 2] 

如果你想永久排序a使用a.sort()

>>> a = [54,35,23,86,3546,87,43,7,2] 
>>> a.sort() 
>>> a 
[2, 7, 23, 35, 43, 54, 86, 87, 3546] 
+0

Woops,不好的注意 - 修正:)謝謝! – Megabeets