您好,登錄后才能下訂單哦!
本文實例為大家分享了python實現按首字母分類查找的具體代碼,供大家參考,具體內容如下
要求:
1.自己查找一些英文詞匯,存儲到某個容器類中
2.根據英文詞匯的首字母進行分類,類似于手機通訊簿中的快速查找功能
3.根據用戶輸入的字母,找到該字母開頭的所有單詞
#coding=utf-8 lexicons=["the","be","of","and","A","to","in","he","have","it","that","for","they","I","with","as","not","on","she","at","by","this","we","you","do","but","from","or","which","one","would","all","will","there","say","who","make","when","can"] while True: startLetter=raw_input("輸入一個字母,列出所有以此字母開頭的單詞:") if len(startLetter)!=1: print "必須是一個字母" else: reLexicons=[] #結果列表 for x in xrange(len(lexicons)): lexicon=lexicons[x] if lexicon[0].lower()==startLetter.lower():#都轉為小寫后比較 開頭字母不區分大小寫 reLexicons.append(lexicon) if len(reLexicons)==0: print "沒有結果" else: for x in xrange(len(reLexicons)): print reLexicons[x]
上面的代碼沒有走第二步,如下代碼 使用字典解決第二步
#coding=utf-8 ''' 邊遍歷,邊構造 key value ''' lexicons=["the","be","of","and","A","to","in","he","have","it","that","for","they","I","with","as","not","on","she","at","by","this","we","you","do","but","from","or","which","one","would","all","will","there","say","who","make","when","can"] lexiconDict={} #分類 保存字典中 lexiconLen=len(lexicons) for x in xrange(len(lexicons)): lexicon=lexicons[x] startLetter=lexicon[0] dictLexicons=lexiconDict.get(startLetter,[]) #空列表說明沒有Key 則添加Key 否則追加Key對應的Value if len(dictLexicons)==0: lexiconDict[startLetter]=[lexicons[x]] else: dictLexicons.append(lexicons[x]) while True: startLetter=raw_input("輸入一個字母,列出所有以此字母開頭的單詞:") if len(startLetter)!=1: print "必須是一個字母" else: lexicons=lexiconDict.get(startLetter.lower(),[]) if len(lexicons)==0: print "沒有結果" else: for x in lexicons: print x
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。