繁体   English   中英

在while循环中访问字典?

[英]Accessing dictionary in while loop?

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

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

忽略我可能犯的任何其他语法错误。

直接迭代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]

甚至更好,您可以使用列表理解

scorer = sum([score[letter] for letter in word.lower()])

while n<=len(word):将索引超出范围

您需要while n<len(word)

现有功能的工作副本

def scrabble_score(word):
    word = word.lower()
    n=0
    scorer=0
    while n<len(word):
        scorer += score[word[n]]
        n+=1
    return scorer

正如其他人指出的那样,一种更干净的方法是遍历单词的字符而不是索引

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM