飘逸的python - 一段统计次数程序的进化

这段程序是从给定的列表中统计各个小伙伴以及他们的出现次数。
littlebuddys = ['jack','terry','john','rooney','ross','kzc','john','ross','ross']


新手程序员

d = {}
for buddy in littlebuddys:
    if buddy not in d:
        d[buddy] = 0
    d[buddy] += 1


信奉EAFP的程序员

d = {}
for buddy in littlebuddys:
    try:
        d[buddy] += 1
    except KeyError:
        d[buddy] = 1


喜欢用默认值避免异常的程序员

d = {}
for buddy in littlebuddys:
    d[buddy] = d.get(buddy,0) + 1


坚定初始化的程序员

d = dict.fromkeys(littlebuddys,0)
for buddy in littlebuddys:
    d[buddy] += 1


生活在水深火热中的程序员

from collections import defaultdict
d = defaultdict(int)
for buddy in littlebuddys:
    d[buddy] += 1


扫地的老太太

from collections import Counter
d = Counter(littlebuddys)


你可能感兴趣的:(程序员,生活,进化)