我对 python 编程很陌生,还没有买一本关于这件事的教科书(我今天从商店或亚马逊买了一本)。同时,您能帮我解决我遇到的以下问题吗?
我有一个这样的字典对象列表:
stock = [
{ 'date': '2012', 'amount': '1.45', 'type': 'one'},
{ 'date': '2012', 'amount': '1.4', 'type': 'two'},
{ 'date': '2011', 'amount': '1.35', 'type': 'three'},
{ 'date': '2012', 'amount': '1.35', 'type': 'four'}
]
我想按金额日期列然后按金额列对列表进行排序,以便排序列表如下所示:
stock = [
{ 'date': '2011', 'amount': '1.35', 'type': 'three'},
{ 'date': '2012', 'amount': '1.35', 'type': 'four'},
{ 'date': '2012', 'amount': '1.4', 'type': 'two'},
{ 'date': '2012', 'amount': '1.45', 'type': 'one'}
]
我现在认为我需要使用 sorted() 但作为初学者,我很难理解我看到的概念。
我试过这个:
from operator import itemgetter
all_amounts = itemgetter("amount")
stock.sort(key = all_amounts)
但这导致列表按字母数字而非数字排序。
有人可以告诉我如何实现这种看似简单的排序吗?谢谢!