【问题标题】:Iterate through dictionary where the value is a list of integers and reorder them遍历字典,其中值是整数列表并重新排序
【发布时间】:2018-11-07 02:24:39
【问题描述】:

我有这个特定的数据集:

{
"Player 1": [0, 1, 3, 5, 7, 0]
"Player 2": [3, 2, 4, 7, 6, 1]
"Player 3": [1, 3, 5, 4, 5, 1]
}

并且需要这个基于从低到高的输出(元素 0 已重新排序列表):

{
"Player 1": [0, 1, 3, 5, 7, 0]
"Player 3": [1, 3, 5, 4, 5, 1]
"Player 2": [3, 2, 4, 7, 6, 1]
}

或此输出基于从高到低(元素 0 已重新排序列表):

{
"Player 2": [3, 2, 4, 7, 6, 1]
"Player 3": [1, 3, 5, 4, 5, 1]
"Player 1": [0, 1, 3, 5, 7, 0]
}

这里的输出显示了键/值的重新排序,因为每个列表中元素 0 中的值已按从低到高排序。我一直在考虑如何做到这一点,虽然我当前的数据模型不需要每个“条目”都有一个键/值对,但这是最有意义的。

我不太确定如何尽可能高效地进行此操作,例如仅抓取元素 0、创建临时列表、重新排序临时列表并将 dict 条目重新映射到此顺序。

或者,搜索列表并按照从高到低、从低到高的顺序重新排序,并在每个元素变为最低可用或最高可用时将其弹出,然后从顶部开始。

实现这一目标的最有效方法是什么?

【问题讨论】:

标签: algorithm sorting python-3.6


【解决方案1】:

你可以使用sorted

x = {"Player 1": [0, 1, 3, 5, 7, 0],
     "Player 2": [3, 2, 4, 7, 6, 1],
     "Player 3": [1, 3, 5, 4, 5, 1]}


output = dict(sorted(x.items(), key = lambda x: x[1][0]))
output_reverse = dict(sorted(x.items(), key = lambda x: x[1][0], reverse=True))

print(output)
print(output_reverse)


# output,

{'Player 1': [0, 1, 3, 5, 7, 0], 'Player 3': [1, 3, 5, 4, 5, 1], 'Player 2': [3, 2, 4, 7, 6, 1]}
{'Player 2': [3, 2, 4, 7, 6, 1], 'Player 3': [1, 3, 5, 4, 5, 1], 'Player 1': [0, 1, 3, 5, 7, 0]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2021-04-21
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多