문제

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??

도움이 되었습니까?

해결책

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

다른 팁

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

shortLifeItems = sorted(shortLifeItems, key=lambda list: list[0])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top