banner

© 2004-21 ict4u.net

Sorting a nested list

The code below demonstrates how to use the Sorted function, specifying a key to sort a nested list with an arbitrary length

# Author: A Knifton
# Date: 29 Jan 2019
# Purpose: Sort a nested list using the sorted function
#          NOTE: the length of the nested list can be infinite


# initialise the list of fruit with cost
listFruit = [["Apple", 23],
             ["Apricots", 25],
             ["Avocado", 98],
             ["Banana", 12],
             ["Blackberry", 23],
             ["Blueberries", 35],
             ["Cherries", 45],
             ["Coconut", 67],
             ["Cranberry", 89],
             ["Gooseberry", 46],
             ["Grapefruit", 56],
             ["Kiwi", 45],
             ["Kumquat", 78],
             ["Lemon", 56],
             ["Lime", 40],
             ["Lychee", 42],
             ["Mango", 89],
             ["Melon", 56],
             ["Nectarine", 43],
             ["Orange", 22],
             ["Papaya", 52],
             ["Peach", 37],
             ["Pear", 67],
             ["Pineapple", 83],
             ["Plum", 25],
             ["Prunes", 12],
             ["Raspberries", 49],
             ["Strawberries", 87],
             ["Tangerine", 34]]


def lastitem(list):
    #Use the reverse key to
    #find the last data item of the nested list
    last = list[-1]
    return last


def sortnestedlist(list):
    #SORTED iterates through the list making a new copy so the original data is preserved
    #provide it with the last data item of the nested list as a key
    sortedList = sorted(list,key=lastitem)
    return sortedList


fruitCosts = sortnestedlist(listFruit)

print("Using Nested Lists\n")

for friutData in listFruit:
    print("{:<12} {:0.2f}p".format(friutData[0],friutData[1]/100))

# The most expensive item is the last. Find it using the reverse index
print ("The most expensive fruit is {} costing {:0.2f}p".format(fruitCosts[-1][0],fruitCosts[-1][1]/100))