我试图从最小到最大整数对列表进行排序。不幸的是,当我尝试运行它时,出现上述错误。ValueError:list.remove(x):x不在列表中python
Traceback (most recent call last):
File "lesson_4/selection_sort.py", line 24, in <module>
print selection_sort([-8, 8, 4, -4, -2, 2]) # [-8, -4, -2, 2, 4, 8]
File "lesson_4/selection_sort.py", line 14, in selection_sort
lst.remove(min)
ValueError: list.remove(x): x not in list
这里是selection_sort.py
的代码def selection_sort(lst):
sorted = []
list_len = len(lst) # Store this now because our loop will make it
# smaller
min = lst[0]
i = 1
while list_len > 0:
while i < list_len:
item = lst[i]
if item < min:
min = item
i += 1
lst.remove(min)
sorted.append(min)
return sorted
# Test Code
print "Testing"
print selection_sort([-8, 8, 4, -4, -2, 2]) # [-8, -4, -2, 2, 4, 8]
感谢帮助我!
你知道排序函数,对吗? https://docs.python.org/2/library/functions.html#sorted – ballsatballsdotballs 2014-10-30 20:46:09
另外,你永远不会改变list_len的值 – ballsatballsdotballs 2014-10-30 20:48:05
而循环不修改列表 – Hackaholic 2014-10-30 20:49:13