【问题标题】:Sort python dictionary with value as list将值作为列表的python字典排序
【发布时间】:2020-08-06 08:47:58
【问题描述】:

如果我们想根据列表的所有索引进行比较,而不仅仅是第一个元素。如果列表相同,则按键排序。列表的长度也是事先不知道的。在那种情况下如何对键进行排序。下面是例子:

{'A': [5, 0, 0], 'B': [0, 2, 3], 'C': [0, 3, 2]}

输出:

[A、C、B]

说明:A 位于第 1 位,因为第 0 索引 5 最高,其余为 0。C 位于第 2 位,因为 C 的第 2 1 索引与 B 的第 1 索引相比为 3。如您所见,我们需要比较对所有位置进行排序,我们事先不知道数组大小。

我试过下面的代码:

countPos = {'A': [5, 0, 0], 'B': [0, 2, 3], 'C': [0, 3, 2]}
res = sorted(countPos.items(), key=lambda x: ((-x[1][i]) for i in range(3)))

上述代码出错。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python-3.x sorting dictionary


    【解决方案1】:

    我认为找到了一个可行的解决方案。这可能是幼稚的。我鼓励大师们纠正我。

    r = sorted(countPos.items(), key=lambda x: x[0])
    r = dict(r)
    res = sorted(r.items(), key=lambda x: x[1], reverse=True)
    

    所以,首先根据键排序,然后我根据值倒序排序。

    【讨论】:

    • 这里你基本上是在做r = dict(countPos.items()).items()dict( ) 这两个操作是互为逆的,所以r 只是countPos 的一个副本。在重新创建 dict 之前对项目进行排序这一事实没有影响(可以对列表进行排序;对 dict 进行排序实际上没有任何意义)。然后你按值对r 进行排序;写sorted(r.items(), key=lambda x: x[1])sorted(r.values()) 相同。
    猜你喜欢
    • 2012-03-03
    • 2020-04-30
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多