使用未正确排序的列表列表在Python中进行冒泡排序

时间:2017-11-20 16:28:24

标签: python list sorting bubble-sort

我的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'] ......... ..........]
它应该按照列表中的第二个元素进行排序 谢谢!

1 个答案:

答案 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']]