python - 从字典外的列表中获取键值
问题描述
我正在尝试为字典中的每个键计算一个“分数”。键值的值在不同的列表中。简化示例:
我有:
Key_values = ['a': 1, 'b': 2, 'c': 3, 'd': 4]
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}
我想:
Scores = ['player1': 8, 'player2': 7]
解决方案
您可以使用 dict 理解创建它:
Key_values = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}
scores = {player: sum(Key_values[mark] for mark in marks) for player, marks in My_dict.items()}
print(scores)
# {'player1': 8, 'player2': 7}
推荐阅读
- c - CS50 马里奥(更舒适)错误。为什么我的金字塔没有正确对齐?
- c# - 在 C# 中减少 BigInteger 值
- google-apps-script - 在二维数组的一列上使用 map.reduce
- r - 将列变量拆分为新列
- django-rest-framework - 通过 Django restApi 断言
- jira - 查找在特定 JIRA 结构中具有子级的问题的 JQL 是什么?
- reactjs - 更好的方法来更新事件的反应组件
- jenkins - Jenkinsfile:如何为“并行”块提供功能,而不是预定义的地图?
- pyspark - 使用 pyspark 在日期范围上运行 for 循环
- python - 设置 NetworkX 边长