欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)按首字母分類(lèi)查找功能

 更新時(shí)間:2019年10月31日 11:03:30   作者:強(qiáng)強(qiáng)強(qiáng)子  
這篇文章主要介紹了python實(shí)現(xiàn)按首字母分類(lèi)查找功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python實(shí)現(xiàn)按首字母分類(lèi)查找的具體代碼,供大家參考,具體內(nèi)容如下

要求:

1.自己查找一些英文詞匯,存儲(chǔ)到某個(gè)容器類(lèi)中
2.根據(jù)英文詞匯的首字母進(jìn)行分類(lèi),類(lèi)似于手機(jī)通訊簿中的快速查找功能
3.根據(jù)用戶輸入的字母,找到該字母開(kāi)頭的所有單詞

#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("輸入一個(gè)字母,列出所有以此字母開(kāi)頭的單詞:")
 if len(startLetter)!=1:
 print "必須是一個(gè)字母"
 else:
 reLexicons=[] #結(jié)果列表
 for x in xrange(len(lexicons)):
  lexicon=lexicons[x]
  if lexicon[0].lower()==startLetter.lower():#都轉(zhuǎn)為小寫(xiě)后比較 開(kāi)頭字母不區(qū)分大小寫(xiě)
  reLexicons.append(lexicon)
 if len(reLexicons)==0:
  print "沒(méi)有結(jié)果"
 else:
  for x in xrange(len(reLexicons)):
  print reLexicons[x]

上面的代碼沒(méi)有走第二步,如下代碼 使用字典解決第二步

#coding=utf-8
'''
邊遍歷,邊構(gòu)造 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={}
#分類(lèi) 保存字典中
lexiconLen=len(lexicons)
for x in xrange(len(lexicons)):
 lexicon=lexicons[x]
 startLetter=lexicon[0]
 dictLexicons=lexiconDict.get(startLetter,[])
  #空列表說(shuō)明沒(méi)有Key 則添加Key 否則追加Key對(duì)應(yīng)的Value
 if len(dictLexicons)==0:
 lexiconDict[startLetter]=[lexicons[x]]
 else:
 dictLexicons.append(lexicons[x])
while True:
 startLetter=raw_input("輸入一個(gè)字母,列出所有以此字母開(kāi)頭的單詞:")
 if len(startLetter)!=1:
 print "必須是一個(gè)字母"
 else:
 lexicons=lexiconDict.get(startLetter.lower(),[])
 if len(lexicons)==0:
  print "沒(méi)有結(jié)果"
 else:
  for x in lexicons:
  print x

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論