【问题标题】:Sorting DefaultDict() using key values in Python3.x使用 Python3.x 中的键值对 DefaultDict() 进行排序
【发布时间】:2015-05-13 12:43:37
【问题描述】:

我有一个包含类似值的字典

DefaultListOrderedDict([('29.970', [1, 0, 0, 0, 0]), ('100.000', [0, 1, 0, 0, 1]), ('200.000', [0, 0, 1, 0, 0]), ('60.000', [0, 0, 0, 1, 0]), ('0.750', [0, 0, 1, 0, 0]), ('25.000', [0, 0, 0, 0, 1]), ('48.000', [0, 0, 1, 0, 0])])

我想用值对其进行排序

我试过for k,v in sorted(Dict.items(),reverse = True):

但是排序是按这个顺序发生的:

   ['0.750', '100.000', '200.000', '25.000', '29.970', '48.000', '60.000']

我不明白背后的原因。我想知道如何将其排序为:

   ['0.750', '25.000', '29.970', '48.000', '60.000', '100.000', '200.000']

【问题讨论】:

  • 这些是字符串,所以它们是按字典顺序排序的。使用浮点字面量或使用float 函数将它们转换为数字。
  • 这是因为您正在对字符串进行排序。首先将您的字符串字典映射到一个 int 字典: dict = {int(k), v for k, v in dict}
  • 如果你想按那个顺序排序,你为什么用reverse = True
  • @martineau 因为当我使用绘图库映射它时,它实际上是在相反的方向绘图。

标签: python sorting python-3.x ordereddictionary


【解决方案1】:

您应该将键转换为浮点数:

OrderedDict(sorted(your_dict.items(), key=lambda item: float(item[0])))

【讨论】:

  • 如何将其存储回 your_dict 的键?作为排序函数。不会自动将排序后的值存储在库中。
猜你喜欢
  • 2012-04-28
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2015-06-03
  • 2019-07-07
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
相关资源
最近更新 更多