简体   繁体   English

如何在字典中的给定键处找到值的总和?

[英]How to find the sum of values at given keys in a dictionary?

I am trying to create a Blackjack game in Python and I need to change the hand that you're given(strings) into integer values.我正在尝试在 Python 中创建一个二十一点游戏,我需要将您获得的手(字符串)更改为 integer 值。 I made a dictionary to key each string to its respective value, but im not sure about how to turn all the strings into integers and calculate the sum我制作了一个字典来将每个字符串键入其各自的值,但我不确定如何将所有字符串转换为整数并计算总和

numbers = ["A", "B", "C", "D"]
values = {
    "A": 1,
    "B": 2,
    "C": 3,
    "D": 4
}

for i in numbers:
    numbers[i] = values[i]
    print(numbers[i])

This is simplification of my code so far到目前为止,这是我的代码的简化

You are close, all that is missing is a way to accumulate the values you encounter in your loop.您很接近,所缺少的只是一种累积您在循环中遇到的值的方法。

total = 0  # start counting from 0

for k in numbers:
    total += values[k]  # for each value add it to the total

print(total)  # print the total

Alternatively, you can use the sum builtin function like so.或者,您可以像这样使用内置的sum function 。 This is probably what would be the preferred way.这可能是首选的方式。

total = sum(value[k] for k in numbers)

Notice that in your case, the list numbers corresponds exactly to the keys of the dict values .请注意,在您的情况下,列表numbers与 dict values的键完全对应。 In your context, it does not seem it will always be the case, but if it were you could do something even simpler using the dict.values method.在您的上下文中,情况似乎并非总是如此,但如果是这样,您可以使用dict.values方法做一些更简单的事情。

total = sum(values.values())

You just need to print the sum at the end of the loop, rather than printing each element in the loop.您只需要在循环结束时打印总和,而不是打印循环中的每个元素。

for i in numbers:
    numbers[i] = values[i]
print(sum(numbers))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM