python計算字母出現次數


pyschools Topic 8: Question 7的題目:給定一個單詞,輸出字母及字母出現次數

Write a function countLetters(word) that takes in a word as argument and returns a dictionary that counts the number of times each letter appears.

python真是方便,可以一行代碼搞定

def countLetters(word):
    return dict(sorted([(l,word.count(l)) for l in set(word)]))
print(countLetters('google'))
{'e': 1, 'g': 2, 'l': 1, 'o': 2}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM