英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论