将两个Python列表合并成一个排序后的字典。

huangapple go评论72阅读模式
英文:

Coalescing two python lists into a sorted dict

问题

我可以使用以下代码将它们合并成一个按照同情值降序排列的字典:

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

这个代码更简洁一些。

英文:

Say I have these:

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

and I wanted to merge those into a dictionary like this, with sorting showing on the compassion value in descending order.

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

I can do it using:

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

It does seem a bit congested. Is there a more 'elegant' solution for this?

答案1

得分: 2

尝试这个:

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}

或者使用operator.itemgetter

from operator import itemgetter
dict(sorted(zip(people, compassion), key=itemgetter(1), reverse=True))
# {'obi': 10, 'anakin': 5, 'palpatine': 0}
英文:

Try this:

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}

Or with operator.itemgetter:

from operator import itemgetter
dict(sorted(zip(people, compassion), key=itemgetter(1), reverse=True))
# {'obi': 10, 'anakin': 5, 'palpatine': 0}

答案2

得分: 2

res = dict(sorted(zip(people, compassion), key=lambda x: -x[1]))
英文:

zip the two lists, together, then use sorted with the number negated as the key.

res = dict(sorted(zip(people, compassion), key=lambda x: -x[1]))

答案3

得分: 0

你可以对这两个列表的组合进行排序后再创建元组:

d = {p: c for c, p in sorted(zip(compassion, people), reverse=True)}

print(d)
# {'obi': 10, 'anakin': 5, 'palpatine': 0}
英文:

You could sort the tuples from the zipped combination of the two lists:

d = {p:c for c,p in sorted(zip(compassion,people),reverse=True)}

print(d)
# {'obi': 10, 'anakin': 5, 'palpatine': 0}

huangapple
  • 本文由 发表于 2023年2月18日 00:25:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定