在python中按字母顺序(带数字)打印列表

时间:2014-04-07 02:50:21

标签: python list alphabetical

我需要打印那些多个列表,但需要按字母顺序打印,.sort不会工作,因为涉及到数字。

"""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]))

所以打印出来:

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

当它打印时:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以使用sorted这样的功能

for item in sorted(shortLifeItems):
    ...

它会比较列表中的每个项目,并按排序顺序返回项目。当它比较像这样的嵌套列表时,它首先比较两个项目的第一个元素,如果它们相等,则第二个元素相等,如果它们相等,则第三个元素继续比较,直到结束。

您可以阅读有关如何在Python中比较各种序列的更多信息,here

答案 1 :(得分:0)

您需要明确排序列表。以下是诀窍:

shortLifeItems = sorted(shortLifeItems, key=lambda list: list[0])
相关问题