【发布时间】:2012-06-20 07:02:12
【问题描述】:
我对 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)
但这导致列表按字母数字而非数字排序。
有人可以告诉我如何实现这种看似简单的排序吗?谢谢!
【问题讨论】:
-
你为什么不把你的dict中的数据转换成数字呢?看起来这样会更好。
-
您的
stock不是有效的 Python。请修复它
标签: python sorting numeric alphanumeric