Skip to main content
 首页 » 编程设计

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

2025年05月04日8mfryf

我需要打印那些多个列表,但它需要按字母顺序打印,.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       

有什么建议吗?

请您参考如下方法:

您可以使用 sorted像这样的功能

for item in sorted(shortLifeItems): 
    ... 

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

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