python - python 中的字典 : summing the values returned from searching the keys

标签 python dictionary sum

我刚刚学习 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

这里:

  1. for l in word 遍历word的字母;
  2. SCRABBLE_LETTER_VALUES[l]获取SCRABBLE_LETTER_VALUES的对应条目;
  3. sum(...) 将它们相加。

sum() 中的构造称为 generator expression .

关于python - python 中的字典 : summing the values returned from searching the keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15177462/

相关文章:

mysql - 使用 GROUP BY 计算没有重复行的 SUM

mysql - 根据多个 id 对多个表中的列求和

dictionary - 如何将字典字典转换为 Ansible vars 文件中的字典列表?

python - Altair 分层图表 : How to sum over charts?

python - 使用命令行时出现 App Engine 问题

python - 在 Mavericks 上运行 Mercurial

python - 实现抽象属性而不需要在 child 中重新定义 __init__

android - 非托管 Google Play 应用内产品的服务器端验证的正确 python 方法是什么?

java - 如何在android中更改位置更改时更改标记位置

python:循环每个键有多个值的字典