【问题标题】:Numeric sort of list of dictionary objects字典对象列表的数字排序
【发布时间】: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


【解决方案1】:

您的排序条件对于operator.itemgetter 来说太复杂了。您将不得不使用 lambda 函数:

stock.sort(key=lambda x: (int(x['date']), float(x['amount'])))

all_amounts = lambda x: (int(x['date']), float(x['amount']))
stock.sort(key=all_amounts)

【讨论】:

  • 哇!那非常快,正是我所需要的。谢谢 eumiro,我将在接下来的一个小时里尝试弄清楚这一切意味着什么:-)
  • 试试all_amounts[stock[0]],看看它是如何构建一个元组进行排序的。
【解决方案2】:

首先将您的数据转换为适当的格式:

stock = [
    { 'date': int(x['date']), 'amount': float(x['amount']), 'type': x['type']}
    for x in stock
]

现在stock.sort(key=all_amounts) 将返回正确的结果。

由于您似乎是编程新手,如果可以的话,这里有一个一般性建议:

正确的数据结构是成功的 90%。不要试图通过编写更多代码来解决损坏的数据。创建一个适合您的任务的结构并尽可能少地编写代码。

【讨论】:

    【解决方案3】:

    你也可以利用python的排序是stable

    stock.sort(key=lambda x: int(x["amount"]))
    stock.sort(key=lambda x: int(x["date"]))
    

    由于具有相同键的项目在排序时保持其相对位置(它们从不交换),因此您可以通过多次排序来构建复杂的排序。

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      相关资源
      最近更新 更多