首页 > 解决方案 > 如何在不使用任何导入函数的情况下提取 2 个嵌套字典的值并将它们各自的值相加?

问题描述

我有一本看起来像这样的字典

{A:{'score': 0, 'throw1': [3, 2, 5, 6], 'throw2': [1, 5, 5, 1]},
 'B': {'score': 0, 'throw1': [2, 2, 3, 6], 'throw2': [6, 4, 2, 2]}}

A 和 B 是这个游戏中的玩家,而 throw1 和 throw2 是他们的掷骰子。每个玩家有 4 次尝试。

我的问题是我如何从字典中提取 throw1 和 throw2 并将他们各自的尝试加在一起为每个玩家。例如,玩家 A 第一次尝试两次投掷都投了 3 和 1。我希望答案是 4

标签: python-3.x

解决方案


您可以使用zip返回元组迭代器的

data = {'A': {'score': 0, 'throw1': [3, 2, 5, 6], 'throw2': [1, 5, 5, 1]},
        'B': {'score': 0, 'throw1': [2, 2, 3, 6], 'throw2': [6, 4, 2, 2]}}

player_A_1_results = data['A']['throw1']
player_A_2_results = data['A']['throw2']

for f, s in zip(player_A_1_results, player_A_2_results):
    print(f + s)

推荐阅读