Python 中的冒泡排序使用的列表列表排序不正确
Bubble sort in Python using list of lists not ordering correctly
我的 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']... ............... ]
它应该按列表中的第二个元素排序。
谢谢!
您需要将值转换为整数:
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']]
我的 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']... ............... ]
它应该按列表中的第二个元素排序。
谢谢!
您需要将值转换为整数:
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']]