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