我有多本可预测的词典。每个字典包含3个元素。如何从每本词典中提取特定键并找到总值?
player_A = {
"kills": 15
"death": 3
"kda": 5
}
player_B = {
"kills": 20
"death": 4
"kda": 5
}
:
player_ZA = {
"kills": 35
"death": 7
"kda": 5
}
比方说,我想找出所有玩家的总击杀数。我应该如何访问词典中所有名为“ kill”的键并找到这些键的总和?
即。预期的输出类似于:
sum(15 + 20 + ... + 35)
答案 0 :(得分:2)
player_a = {"kills": 15, "death": 3, "kda": 5}
player_b = {"kills": 20, "death": 4, "kda": 5}
player_c = {"kills": 35, "death": 7, "kda": 5}
players = [player_a, player_b, player_c]
total_kills = sum(player["kills"] for player in players)
答案 1 :(得分:0)
尝试这个:
player_A = {"kills": 15, "death": 3, "kda": 5}
player_B = {"kills": 20, "death": 4, "kda": 5}
player_ZA = {"kills": 35, "death": 7, "kda": 5}
def f(x):
result = 0
for key, value in x.items():
if key.startswith("player"):
result += value["kills"]
return result
print(f(globals()))
或者这个:
player_A = {"kills": 15, "death": 3, "kda": 5 }
player_B = { "kills": 20, "death": 4, "kda": 5 }
player_ZA = { "kills": 35, "death": 7, "kda": 5 }
def f(x):
return sum(value["kills"] for key, value in x.items() if key.startswith("player"))
print(f(globals()))
答案 2 :(得分:0)
您也可以执行以下操作:-
player_a = {"kills": 15, "death": 3, "kda": 5}
player_b = {"kills": 20, "death": 4, "kda": 5}
player_c = {"kills": 35, "death": 7, "kda": 5}
player_d = {'death':5} # If dictionary does not contains 'kills' key.
players = [player_a , player_b , player_c, player_d]
l = []
for player in players:
try:
l.append(player['kills'])
except Exception as e:
continue
print(f"Total kills are {sum(l)}")
输出
Total kills are 70
希望您能学到新知识。
答案 3 :(得分:0)
这是将"kills"
值相加的另一种方法(函数式编程):
player_A = {"kills": 15, "death": 3, "kda": 5}
player_B = {"kills": 20, "death": 4, "kda": 5}
player_ZA = {"kills": 35, "death": 7, "kda": 5}
f = lambda x: sum(map(lambda j: x[j]["kills"], filter(lambda i: i.startswith("player"), x)))
print(f(globals()))