Tzu-ping Chung
March 26, 2015
190

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

March 26, 2015

## Transcript

3. ### 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]

6. ### counts  =  {}   for  name  in  namelist:

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

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

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

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

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

sorted(namelist),                    key=lambda  n:  n[0]):          count  =  len(list(v)) 馄䌃

13. ### 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
14. ### for  k,  v  in  groupby(

sorted(namelist),                    key=lambda  n:  n[0]):          count  =  len(list(v)) Loop Implicit loop

16. ### • name = str(random.random())[2:] • Exclude import overhead • Benchmarking

against dict + LBYL

23. ### • try is cheap, except is (more) expensive • If

you hit often, use try-except • If you fail often, use .get

26. ### .__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
27. ### .__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!
28. ### • .get is generally much slower, due to argument unpacking

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