簡體   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