Upgrade to Pro — share decks privately, control downloads, hide ads and more …

計算名字 list 中開頭字母的人數

計算名字 list 中開頭字母的人數

所謂小題大作就是這個概念?我真的不知道簡介要寫什麼。

如果你真的想知道為什麼 .get 很慢,請看 http://www.slideshare.net/ya790026/why-is-a1-fast-than-aget1

Tzu-ping Chung

March 26, 2015
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. counts  =  {}   for  name  in  namelist:    

         if  name[0]  not  in  counts:                  counts[name[0]]  =  1          else:                  counts[name[0]]  +=  1   for  key  in  counts:          count  =  counts[key]
  2. counts  =  {}   for  name  in  namelist:    

         try:                  counts[name[0]]  +=  1          except  KeyError:                  counts[name[0]]  =  1   for  key  in  counts:          count  =  counts[key]
  3. counts  =  {}   for  name  in  namelist:    

         val  =  counts.get(name[0],  0)          counts[name[0]]  =  val  +  1   for  key  in  counts:          count  =  counts[key]
  4. from  collections  import  defaultdict   counts  =  defaultdict(lambda:  0)  

    for  name  in  namelist:          counts[name[0]]  +=  1   for  key  in  counts:          count  =  counts[key]
  5. from  collections  import  Counter   counts  =  Counter(    

         name[0]  for  name  in  namelist   )   for  key  in  counts:          count  =  counts[key]
  6. from  itertools  import  groupby   for  k,  v  in  groupby(

                     sorted(namelist),                    key=lambda  n:  n[0]):          count  =  len(list(v))
  7. from  itertools  import  groupby   for  k,  v  in  groupby(

                     sorted(namelist),                    key=lambda  n:  n[0]):          count  =  len(list(v)) 馄䌃
  8. counts  =  {}   for  name  in  namelist:    

         if  name[0]  not  in  counts:                  counts[name[0]]  =  1          else:                  counts[name[0]]  +=  1   for  key  in  counts:          count  =  counts[key] Loop
  9. for  k,  v  in  groupby(          

           sorted(namelist),                    key=lambda  n:  n[0]):          count  =  len(list(v)) Loop Implicit loop
  10. • try is cheap, except is (more) expensive • If

    you hit often, use try-except • If you fail often, use .get
  11. .__getitem__ • Check argument type (string optimisation) • Value lookup

    • Return value on success • Extra checks and KeyError on failure .get • Argument unpacking
 • Value lookup • Return the value on success • Return default value on failure
  12. .__getitem__ • Check argument type (string optimisation) • Value lookup

    • Return value on success • Extra checks and KeyError on failure .get • Argument unpacking
 • Value lookup • Return the value on success • Return default value on failure Super slow! Super fast!
  13. • .get is generally much slower, due to argument unpacking

    • If you fail often, .get’s default value might make up speed