中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python實現按首字母分類查找功能

發布時間:2020-09-11 23:34:52 來源:腳本之家 閱讀:270 作者:強強強子 欄目:開發技術

本文實例為大家分享了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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

仙桃市| 来安县| 郧西县| 汤原县| 汶上县| 修文县| 长沙县| 南丹县| 虞城县| 卓资县| 同心县| 班玛县| 静安区| 兴安县| 凤翔县| 鄄城县| 城市| 宁都县| 雷波县| 大厂| 长治市| 舒城县| 肥城市| 德兴市| 鄂伦春自治旗| 冷水江市| 长顺县| 攀枝花市| 贵港市| 新泰市| 长泰县| 基隆市| 手游| 江门市| 肇源县| 芮城县| 泸水县| 郎溪县| 普格县| 梅河口市| 灌阳县|