I'm trying to sort a list of integers in Python without using the sort()
function.
我试图在不使用sort()函数的情况下对Python中的整数列表进行排序。
In my code there's an error when the program tries deleting the lowest value from the unordered list.
在我的代码中,当程序尝试从无序列表中删除最低值时出现错误。
I have already rewritten the code and tried different things like .remove()
rather than delete but just can't figure out how to do it.
我已经重写了代码并尝试了不同的东西,比如.remove()而不是删除,但却无法弄清楚如何去做。
unordered = [18 ,13 ,44 ,12,19 ,27,2,31]
print(unordered)
ordered = []
lowest = unordered[0]
indexOfLowest = 0
while len(unordered) > 0:
for number in unordered:
if number < lowest:
lowest = number
indexOfLowest = unordered.index(lowest)
del unordered[indexOfLowest]
ordered.append(lowest)
print(ordered)
1 个解决方案
#1
0
You need to bring some of your initialization into the loop like:
您需要将一些初始化带入循环,如:
Code:
unordered = [18, 13, 44, 12, 19, 27, 2, 31]
print(unordered)
ordered = []
while unordered:
lowest = unordered[0]
index_of_lowest = 0
for i, number in enumerate(unordered):
if number < lowest:
lowest = number
index_of_lowest = i
del unordered[index_of_lowest]
ordered.append(lowest)
print(ordered)
Results:
[18, 13, 44, 12, 19, 27, 2, 31]
[2, 12, 13, 18, 19, 27, 31, 44]
#1
0
You need to bring some of your initialization into the loop like:
您需要将一些初始化带入循环,如:
Code:
unordered = [18, 13, 44, 12, 19, 27, 2, 31]
print(unordered)
ordered = []
while unordered:
lowest = unordered[0]
index_of_lowest = 0
for i, number in enumerate(unordered):
if number < lowest:
lowest = number
index_of_lowest = i
del unordered[index_of_lowest]
ordered.append(lowest)
print(ordered)
Results:
[18, 13, 44, 12, 19, 27, 2, 31]
[2, 12, 13, 18, 19, 27, 31, 44]