Python 在while循环中访问字典?

Python 在while循环中访问字典?,python,dictionary,key,Python,Dictionary,Key,此代码用于根据作为参数给出的单词中包含的字母添加分数: score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4

此代码用于根据作为参数给出的单词中包含的字母添加分数:

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}

def scrabble_score(word):
  word = word.lower()
  n=0
  scorer=0
  while n<=len(word):
    scorer = scorer + score[word[n]]
    n+=1
  return scorer
分数={“a”:1,“c”:3,“b”:3,“e”:1,“d”:2,“g”:2, “f”:4,“i”:1,“h”:4,“k”:5,“j”:8,“m”:3, “l”:1,“o”:1,“n”:1,“q”:10,“p”:3,“s”:1, “r”:1,“u”:1,“t”:1,“w”:4,“v”:4,“y”:4, “x”:8,“z”:10} def拼字游戏分数(单词): word=word.lower() n=0 记分员=0
而n直接迭代
word.lower()
的输出,而不是索引。此外,还可以使用
sum
函数计算所有字典查找的总和

def scrabble_score(word):
    return sum(score[c] for c in word.lower())
一个不太简洁的版本,坚持您原始代码的精神,仍然会直接迭代
word

def scrabble_score(word):
    scorer = 0
    for c in word.lower():
        scorer = scorer + score[c]  # or scorer += score[c]
    return scorer

直接迭代
word.lower()
的输出,而不是索引。此外,还可以使用
sum
函数计算所有字典查找的总和

def scrabble_score(word):
    return sum(score[c] for c in word.lower())
一个不太简洁的版本,坚持您原始代码的精神,仍然会直接迭代
word

def scrabble_score(word):
    scorer = 0
    for c in word.lower():
        scorer = scorer + score[c]  # or scorer += score[c]
    return scorer

你的代码是正确的。然而,有两件事与风格有关

在python中,字符串是可编辑的字符,所以

scorer = 0

for letter in word.lower():
    scorer += score[letter]
更好的是,您可以使用列表理解


你的代码是正确的。然而,有两件事与风格有关

在python中,字符串是可编辑的字符,所以

scorer = 0

for letter in word.lower():
    scorer += score[letter]
更好的是,您可以使用列表理解


while n
while n您的问题是什么?代码在输出中给出错误请比“给出错误”更具体-什么错误以及在哪一行?只需删除=符号:p您的问题是什么?代码在输出中给出错误请比“给出错误”更具体–什么错误,在哪一行?只需删除=符号:p这不是列表理解;这只是一个生成器表达式
sum([score[letter]for letter in word.lower()])
将使用列表理解。@切普纳:正确,我在键入时省略了括号。但是没有理由使用列表理解
sum
只需要一个iterable,生成器就足够了(而且不需要在求和之前计算所有的分数,这样可以节省内存)。@chepner:我知道,但是向第一次看到该语言的人提及生成器表达式似乎有点过分。为什么?它们非常有用,也不难理解;这只是一个生成器表达式
sum([score[letter]for letter in word.lower()])
将使用列表理解。@切普纳:正确,我在键入时省略了括号。但是没有理由使用列表理解
sum
只需要一个iterable,生成器就足够了(而且不需要在求和之前计算所有的分数,这样可以节省内存)。@chepner:我知道,但是向第一次看到该语言的人提及生成器表达式似乎有点过分。为什么?它们非常有用,也不难理解。