Print lists in alphabetical order(with numbers) in python -
i need print multiple lists need printed in alphabetical order, .sort wont work because there numbers involved.
"""define function 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 short shelf life item in shortlifeitems: print("{:^20s}${:^16s}{:^20s}${:^16s}"\ .format((item[0]),item[1],item[2],item[3]))
so prints:
steak $ 10.00 7 $ 10.50 canned corn $ .50 5 $ 0.53
when suppose print:
canned corn $ .50 5 $ 0.53 steak $ 10.00 7 $ 10.50
any suggestions??
you can use sorted
function this
for item in sorted(shortlifeitems): ...
it compares each , every item in list , returns items in sorted order. when compares nested lists this, first compares first element of both items , if equal second , if equal, third , goes on till end.
you can read more how various sequences compared in python, here
Comments
Post a Comment