list,tuple,dict,set常用方法

Python中list,tuple,dict,set常用方法

 

collections模块提供的其它有用扩展类型

from collections import Counter
from collections import defaultdict


c = Counter()
for ch in 'programming':
    c[ch] = c[ch]+1
dd = defaultdict(lambda:0)
dd[0]=dd[0]+1
print(dd[0])
print(c)

结果
-------------------------
1
Counter({'g': 2, 'm': 2, 'r': 2, 'n': 1, 'i': 1, 'a': 1, 'p': 1, 'o': 1})

注意:defaultdict可以设置key不存在时的返回值(不报错),而不像dict[]抛出异常

posted @ 2017-01-01 18:00  welcome_home  阅读(291)  评论(0编辑  收藏  举报