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

长平狐 发布于 2013/08/21 14:22
阅读 57
收藏 0
这段程序是从给定的列表中统计各个小伙伴以及他们的出现次数。
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)



原文链接:http://blog.csdn.net/handsomekang/article/details/9561961
加载中
返回顶部
顶部