使用变量键返回字典值
Returning dict Value with a variable Key
我正在使用单词中的字符来搜索字典的关键字。字典是 SCRABBLE_LETTER_VALUES: { 'a' : 1, 'b' : 3, ...} 等等。
这是我的不完整代码:
"""
Just a test example
word = 'pie'
n = 3
"""
def get_word_score(word, n):
"""
Returns the score for a word. Assumes the word is a
valid word.
The score for a word is the sum of the points for letters
in the word multiplied by the length of the word, plus 50
points if all n letters are used on the first go.
Letters are scored as in Scrabble; A is worth 1, B is
worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
word: string (lowercase letters)
returns: int >= 0
"""
score = 0
for c in word:
if SCRABBLE_LETTER_VALUES.has_key(c):
score += SCRABBLE_LETTER_VALUES.get("""value""")
现在这段代码不完整,因为我还在学习 python,所以我还在思考这个问题,但我卡在 returning a value with a 的方面改变每次迭代的关键。
虽然我可能可以将 c 设置为它匹配的键,然后 return 设置值,但我不确定该怎么做。另外,我想检查一下我是否确实处于正确的思维过程中,可以这么说。
仅供参考,此代码库确实成功进入循环,我只是无法检索值。
感谢指教!
您在每次迭代中都将 score
设为零。您应该在 for
循环之前对其进行初始化。
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
您可以执行以下操作:
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
get()
将 return 如果字典包含键的值,否则它将 return 作为第二个参数传递的默认值(代码段中的 0)。
我正在使用单词中的字符来搜索字典的关键字。字典是 SCRABBLE_LETTER_VALUES: { 'a' : 1, 'b' : 3, ...} 等等。
这是我的不完整代码:
"""
Just a test example
word = 'pie'
n = 3
"""
def get_word_score(word, n):
"""
Returns the score for a word. Assumes the word is a
valid word.
The score for a word is the sum of the points for letters
in the word multiplied by the length of the word, plus 50
points if all n letters are used on the first go.
Letters are scored as in Scrabble; A is worth 1, B is
worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
word: string (lowercase letters)
returns: int >= 0
"""
score = 0
for c in word:
if SCRABBLE_LETTER_VALUES.has_key(c):
score += SCRABBLE_LETTER_VALUES.get("""value""")
现在这段代码不完整,因为我还在学习 python,所以我还在思考这个问题,但我卡在 returning a value with a 的方面改变每次迭代的关键。
虽然我可能可以将 c 设置为它匹配的键,然后 return 设置值,但我不确定该怎么做。另外,我想检查一下我是否确实处于正确的思维过程中,可以这么说。
仅供参考,此代码库确实成功进入循环,我只是无法检索值。
感谢指教!
您在每次迭代中都将 score
设为零。您应该在 for
循环之前对其进行初始化。
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
您可以执行以下操作:
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES.get(c, 0)
return score
get()
将 return 如果字典包含键的值,否则它将 return 作为第二个参数传递的默认值(代码段中的 0)。