我的python程序中的冒泡排序算法似乎未按正确的顺序完成排序或排序。
def sort():
listsImport()
for passnum in range(len(numberLists)-1, 0, -1):
for i in range(passnum):
if numberLists[i][1] > numberLists[i+1][1]:
temp = numberLists[i]
numberLists[i] = numberLists[i+1]
numberLists[i+1] = temp
print(numberLists)
数字列表如下所示:
[['hello','5','1'],['再见','12','8'],['称呼','14,'9'] ......... ..........]
它应该按列表中的第二个元素排序。
谢谢 !
最佳答案
您需要将值转换为整数:
def sort():
numberLists = [['hello','5','1'], ['goodbye', '12', '8'], ['salutations', '14','9']]
for passnum in range(len(numberLists)-1, 0, -1):
for i in range(passnum):
if int(numberLists[i][1]) > int(numberLists[i+1][1]):
temp = numberLists[i]
numberLists[i] = numberLists[i+1]
numberLists[i+1] = temp
return numberLists
输出:
[['hello', '5', '1'], ['goodbye', '12', '8'], ['salutations', '14', '9']]