python - defaultdict
在python时会用到把元组数据整合变成词典
比如统计学生特长:
list1 = dict() list1['张三'] = list(); list1["李四"] = list(); list1["王五"] = list(); list2 = [ ("张三", "会篮球"), ("李四", "会篮球"), ("王五", "会篮球"), ("李四", "会游泳"), ("张三", "会游泳"), ("李四", "会画画"), ("王五", "会画画"), ("王五", "会开车"), ("张三", "会足球"), ("王五", "会足球"), ]; for key,value in list2: list1[key].append(value) print(str(list1))
因为python词典如果key不存在会报错,所以生成词典时用defaultdict会方便很多
defaultdict重写了方法_missing_(key),增加了一个可写的实例变量default_factory,实例变量default_factory被missing()方法使用,如果该变量存在,则用以初始化构造器,如果没有,则为None。其它的功能和dict一样。
from collections import defaultdict as dd #生成字典 list1 = dd(list) list2 = [ ("张三", "会篮球"), ("李四", "会篮球"), ("王五", "会篮球"), ("李四", "会游泳"), ("张三", "会游泳"), ("李四", "会画画"), ("王五", "会画画"), ("王五", "会开车"), ("张三", "会足球"), ("王五", "会足球"), ]; for key,value in list2: list1[key].append(value) print(str(list1))