【问题标题】:Print lists in alphabetical order(with numbers) in python在python中按字母顺序(带数字)打印列表
【发布时间】:2014-04-07 02:50:21
【问题描述】:

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

有什么建议吗??

【问题讨论】:

    标签: python list alphabetical


    【解决方案1】:

    你可以像这样使用sorted函数

    for item in sorted(shortLifeItems):
        ...
    

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

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

    【讨论】:

      【解决方案2】:

      您需要明确地对列表进行排序。以下方法可以解决问题:

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

      【讨论】:

      • 本例不需要key参数。
      猜你喜欢
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      相关资源
      最近更新 更多