用Python按字母顺序打印带编号的列表

2 投票
2 回答
1424 浏览
提问于 2025-04-18 01:39

我需要把这些多个列表打印出来,但要按字母顺序打印。用.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

你需要明确地对你的列表进行排序。下面的代码可以做到这一点:

shortLifeItems = sorted(shortLifeItems, key=lambda list: list[0])
1

你可以这样使用 sorted 函数:

for item in sorted(shortLifeItems):
    ...

这个函数会把列表里的每一个项目进行比较,然后把它们按顺序排列好。当它比较嵌套列表时,首先会比较两个项目的第一个元素,如果相等,就比较第二个元素,如果第二个也相等,就比较第三个,以此类推,一直到最后。

想了解更多关于Python中各种序列是如何比较的,可以在 这里 阅读更多信息。

撰写回答