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))
1
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
相關問題
- 1. php函數返回空字符串。 echo正確地打印字符串;
- 2. 返回語句與打印語句?
- 3. 如何在一個return語句中返回兩個字符串?
- 4. 函數返回的std :: string崩潰沒有return語句,不像它返回int的函數沒有return語句
- 5. 返回「」代替正確的字符串
- 6. 返回正確的字符串格式
- 7. 字符串返回語句JS
- 8. 的NSString:返回值或空字符串
- 9. JSON字符串化返回null,但文件撰寫打印出正確
- 10. 返回字符串值而不使用Java中的返回語句
- 11. 打印返回值
- 12. 爲什麼空語句ToString()返回一個空字符串?
- 13. 值打印功能正確,但返回時是None
- 14. 返回語句'RETURN TO'是什麼?
- 15. 將打印出字符在return語句
- 16. 怎樣才能返回return語句不返回元素?
- 17. select語句的返回值
- 18. OpenFileDialog.FileName返回空字符串
- 19. Textbox.value返回空字符串
- 20. Edittext返回空字符串
- 21. p:inputTextarea返回空字符串
- 22. preg_replace()返回空字符串
- 23. jHtmlArea返回空字符串
- 24. md5返回空字符串
- 25. file_get_contents返回空字符串
- 26. get_FOO_display返回空字符串
- 27. RegEx返回空字符串
- 28. List.OrderBy返回空字符串
- 29. 返回空字符串
- 30. json_decode返回空字符串
您是否可以更新縮進以匹配正在執行的內容?很難判斷它是否輸入錯誤,或者縮進是否是其中的一部分問題。 – ryachza
因爲你正在調用你的函數兩次,到第二次調用時,'a'已經是空的。爲每個函數調用創建一個'a'副本,或者只調用一次'section'。 –
你正在改變列表順序'彈出'最小元素。這是令人難以置信的**效率低下,但順便說一句,它不完全清楚你正在描述什麼問題,但絕對,第二次你調用'選擇(一)'不會工作,因爲'a'將是一個空名單。 –