對於另外一個班輪解決方案:
def count_letters(word): return len(filter(lambda x: x not in " ", word))
這是通過使用過濾功能,它可以讓你挑傳給你作爲傳遞一個布爾值函數時返回true列表的元素第一個參數。我正在使用lambda函數爲此目的創建一個快速的一次性函數。
>>> count_letters("This is a test")
11
您可以輕鬆地擴展這個排除你喜歡的任何字符選擇:
def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word))
>>> count_letters ("This is a test", "aeiou ")
7
編輯:但是,你希望得到自己的代碼來工作,所以這裏有一些想法。第一個問題是你沒有設置Counter對象的列表來計數。但是,由於您正在查找字母的總數,因此您需要再次將單詞連接在一起,而不是單獨計算每個單詞。循環添加每個字母的數量並不是必須的,因爲您可以提取值的列表並使用「sum」來添加它們。
這裏有一個版本,這是接近你的代碼,因爲我可以做到,沒有循環:
from collections import Counter
import string
def count_letters(word):
wordsList = string.split(word)
count = Counter("".join(wordsList))
return sum(dict(count).values())
word = "The grey old fox is an idiot"
print count_letters(word)
編輯:在回答評論問爲什麼不使用一個for循環,這是因爲它不是必要的,並且在許多情況下,使用許多隱含的方式在Python中執行重複性任務可能會更快,更易於閱讀和更高的內存效率。
例如,我可以寫
joined_words = []
for curr_word in wordsList:
joined_words.extend(curr_word)
count = Counter(joined_words)
,但這樣做我拉閘分配額外的陣列,並通過Python解釋我的解決方案執行循環:
count = Counter("".join(wordsList))
將執行在大量優化的,編譯的C代碼中。我的解決方案不是簡化該循環的唯一方法,但它是一種方法。
有什麼錯誤? –
錯誤在於它返回0 –
'len(word.replace(「」,「」))' – Blorgbeard