gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:33 25 4
gpt4 key购买 nike

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

关于python - 在 python 中按字母顺序(带数字)打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com