首页 > 解决方案 > 如何在python中创建for循环以使用单词的字符访问字典的键值

问题描述

所以,我有一个包含整个字母表的字典,其中字符作为键,1-9 之间的不同数字作为值。

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}

我想知道的是,给定一个单词,如何找到与键关联的相应键值的总和,即。单词中的字符。

例如

abc

将产生 7。

我写了以下代码

def get_word_score(word,n):
    """Assumes the word is correct and calculates the score, will need to handle strings with mixed cases"""
    sum = 0
    word_low = word.lower()
    for i in word_low:
        sum += LETTER_VALUES[i]
    return sum

任何帮助将不胜感激 :)

标签: pythonfunctiondictionaryfor-loop

解决方案


看来你叫错了dictionary:它应该是 SCRABBLE_LETTER_VALUES (假设它是在上面全局定义的)。其次,不确定n您的函数签名中的作用是什么?因为没用过?!

或者,您可以简化处理以一次性使用generator expression和传递:sum

请注意 - 在 Python 中,字符串(单词)也是可以迭代的可交互对象。

LETTER_VALUES 是您的原件。字典。

def get_word_score(word):
    return sum(LETTER_VALUES[ch] for ch in word.lower())
    

In [4]: get_word_score("ABBA")
Out[4]: 8

In [5]: get_word_score("Dr")
Out[5]: 3

In [6]: get_word_score('Zoo')
Out[6]: 12

推荐阅读