我刚刚学习 Python,所以这可能非常简单。我试图在字典中找到与键匹配的值并将它们相加。我已经编写了找到值的代码并且可以打印它(在 Online Python Tutor 中测试了这个以查看会发生什么)但是我无法弄清楚如何将它作为返回正确分数的总分(6 ).我知道目前这不是一个函数。
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
word ='tact'
score =0
for i in range(len(word)):
for letter,score in SCRABBLE_LETTER_VALUES.items():
if letter == word[i]:
print score
最佳答案
>>> sum(SCRABBLE_LETTER_VALUES[l] for l in word)
6
这里:
for l in word
遍历word
的字母;SCRABBLE_LETTER_VALUES[l]
获取SCRABBLE_LETTER_VALUES
的对应条目;sum(...)
将它们相加。
sum()
中的构造称为 generator expression .
关于python - python 中的字典 : summing the values returned from searching the keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15177462/