Search code examples
pythonpython-2.7nested-listsbubble-sort

How to take organize nested list in descending order using bubble sort?


Currently I'm working with a nested list that prints out area names and the associated number of people in a group. I've found out how to turn the numbers in the nested list into integers and keep the names as strings:

def Top5_bottom5():
    with open("APExam.txt", "r") as in_file:
        nested = [line.strip().split(',') for line in in_file][1:]
        nested = [line[0:1] + [int(x) for x in line[1:]] for line in nested]
        print nested

This prints the following list of states and stats:

[['Alabama', 126, 79, 17], ['Alaska', 21, 100, 10], ['Arizona', 190, 59, 16], ['Arkansas', 172, 49, 28], ['California', 4964, 76, 22] ...]

I'm trying to use a bubble sort function similar to this:

def bubble(badList):
    length = len(badList) - 1
    unsorted = True

    while unsorted:
        for element in range(0,length):
            unsorted = False
            if badList[element] > badList[element + 1]:
                hold = badList[element + 1]
                badList[element + 1] = badList[element]
                badList[element] = hold
                print badList
            else:
                unsorted = True

But from this code I can't quite figure out how to specify the [1]th element in each sublist that I want it to sort in descending order by. So I'm trying to get it look something more like this:

[['California', 4964, 76, 22], ['Arizona', 190, 59, 16], ['Arkansas', 172, 49, 28], ['Alabama', 126, 79, 17],['Alaska', 21, 100, 10]... ]

Basically what it boils down to is how do I sort nested lists using bubble sort on specific elements of those sublists?


Solution

  • Instead of if badList[element] > badList[element + 1], try if badList[element][1] > badList[element + 1][1]. You can just keep using the [] notation to look into arbitrary nesting depths.