1. 程式人生 > 程式設計 >python實現按首字母分類查詢功能

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

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。