我的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'],['goodbye','12','8'],['salutations','14,'9'] ......... ..........]
它应该按照列表中的第二个元素进行排序
谢谢!
答案 0 :(得分:2)
您需要将值转换为整数:
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']]