1. 程式人生 > >Python 中找出字串中出現頻率最高的字母

Python 中找出字串中出現頻率最高的字母

發現一個學Python的好網站 https://py.checkio.org

第一題大概意思就是找出一個字串中出現頻率最高字母

我的思路也是直接,弄個字典,遍歷字串,將鍵值對填進字典裡,健就是字母,值就是出現了幾次,再查下字典裡最大的值即可。

上我的程式碼

import re, string
def checkio(text):
    #先變小寫再排序
    text ="".join((lambda x:(x.sort(),x)[1])(list(text.lower()))) 
    dicts = {}
    #遍歷字串
    for i in text[0
:]: #篩選只有字母的 if i.isalpha(): #有則加一,無則為一 if i in dicts: dicts[i] = dicts[i] + 1 else: dicts[i] = 1 test = 0 a = '' #遍歷所有key值 for j in dicts.keys(): #大的留下,小的直接過 if dicts[j] > test: test = dicts[j] a = j #返回值
return a if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio("Hello World!") == "l", "Hello test" assert checkio("How do you do?") == "o", "O is most wanted" assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case." assert checkio("AAaooo!!!!") == "a", "Only letters." assert checkio("abe") == "a", "The First." print("Start the long test") assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." print("The local tests are done.")

外國的大神是這樣寫的 兩句話

def checkio(text):
    #我懂第一步是變小寫
    text = text.lower()
    #what? max不就是個比大小的?咋這麼牛逼呢?
    return max(string.ascii_lowercase, key=text.count)

其中 string.ascii_lowercase這個列印結果是abcdefghijklmnopqrstuvwxyz,
這個就是字母表小寫字母排序輸出,key=text.count 先要理解count這個方法 ,count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置,那就是我挨個在count裡傳入字母,它也挨個返回這個字母返回的次數。max裡就是比大小咯,輸出第一個。神奇!!!