[英]What is an efficient way to find the minimum sum of multiple dictionary values, given keys of mutually exclusive integers?
[英]How to find the sum of values at given keys in a dictionary?
我正在尝试在 Python 中创建一个二十一点游戏,我需要将您获得的手(字符串)更改为 integer 值。 我制作了一个字典来将每个字符串键入其各自的值,但我不确定如何将所有字符串转换为整数并计算总和
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])
到目前为止,这是我的代码的简化
您很接近,所缺少的只是一种累积您在循环中遇到的值的方法。
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
或者,您可以像这样使用内置的sum
function 。 这可能是首选的方式。
total = sum(value[k] for k in numbers)
请注意,在您的情况下,列表numbers
与 dict values
的键完全对应。 在您的上下文中,情况似乎并非总是如此,但如果是这样,您可以使用dict.values
方法做一些更简单的事情。
total = sum(values.values())
您只需要在循环结束时打印总和,而不是打印循环中的每个元素。
for i in numbers:
numbers[i] = values[i]
print(sum(numbers))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.