【问题标题】:Coalescing two python lists into a sorted dict将两个 python 列表合并成一个排序的字典
【发布时间】:2023-02-18 00:34:32
【问题描述】:

说我有这些:

people = ['palpatine', 'obi', 'anakin']
compassion = [0, 10, 5]

我想将它们合并到这样的字典中,并按降序显示同情值。

{
   "obi": 10,
   "anakin": 5,
   "palpatine: 0
}

我可以使用:

dict(sorted(dict(map(lambda i, j: (i, j), people, compassion)).items(), key=lambda x:x[1], reverse=True))

看起来确实有点拥挤。有没有更“优雅”的解决方案?

【问题讨论】:

  • map(lambda i, j: (i, j), people, compassion)zip(people, compassion)相同

标签: python python-3.x


【解决方案1】:

尝试这个:

people = ['palpatine', 'obi', 'anakin']
compassion = [0, 10, 5]
dict(sorted(zip(people, compassion), key=lambda x: x[1], reverse=True))
# {'obi': 10, 'anakin': 5, 'palpatine': 0}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 2013-11-02
    • 1970-01-01
    • 2022-10-05
    • 2017-07-23
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多