Question

I need to print those multiple lists but it need to be printed in alphabetical order, .sort wont work because there is numbers involved.

"""define a function to retrive short shelf life items in alphabetical order"""
def retrieveShortShelfLifeItems(oneItemList):
    if shelfLife <= 7:
        shortLifeItemsList.append(oneItemList)
    return shortLifeItemsList

#initializes short shelf life list
shortLifeItemsList = []

shortLifeItems = [['Steak', ' 10.00', ' 7', '10.50'], ['Canned Corn', ' .50', ' 5', '0.53']]

#print items with short shelf life
for item in shortLifeItems:
    print("{:^20s}${:^16s}{:^20s}${:^16s}"\
          .format((item[0]),item[1],item[2],item[3]))

so it prints:

   Steak        $      10.00               7         $     10.50      
Canned Corn     $       .50                5         $      0.53      

when it is suppose to print:

Canned Corn     $       .50                5         $      0.53
   Steak        $      10.00               7         $     10.50      

Any suggestions??

Was it helpful?

Solution

You can use sorted function like this

for item in sorted(shortLifeItems):
    ...

It compares each and every item in the list and returns the items in the sorted order. When it compares the nested lists like this, it first compares the first element of both the items and if they are equal then the second and if they are equal, then the third and goes on till the end.

You can read more about how various sequences are compared in Python, here

OTHER TIPS

You will need to explicitly sort your list of lists. The following would do the trick:

shortLifeItems = sorted(shortLifeItems, key=lambda list: list[0])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top