python - 如何在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
任何帮助将不胜感激 :)
解决方案
看来你叫错了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
推荐阅读
- ios - 是否存在适用于 Swift (iOS) 的 Binance API?
- postgresql - pgAdmin4 + WSL2:看不到使用其他客户端创建的数据库
- python - 将 JSON 数据的子集转换为 CSV
- svg - css中的webpack相对url,创建复制的导出svg文件
- r - 早期评估值的数据表
- c# - C# TryGet 在 .NET 4.x/Standard 2.0 中使用 Nullable Reference Annotation
- reactjs - 来自私有存储库的组件的无效挂钩调用
- vim - vim 在命令模式下引用和转义
- android - 如何使用 OkHttp 进行 HTTPS 连接
- python - 每周二氧化碳浓度的 Matplotlib Python 热图