gpt4 book ai didi

python - Python中使用列表列表进行冒泡排序的顺序不正确

转载 作者:行者123 更新时间:2023-12-01 02:26:02 25 4
gpt4 key购买 nike

我的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)

号码列表如下所示:
[['你好','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']]

关于python - Python中使用列表列表进行冒泡排序的顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47396680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com