Python collections.defaultdict()
2016-03-25 13:23
417 查看
两个代码例子
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = collections.defaultdict(list) for k, v in s: print k, v d[k].append(v) print d print list(d.items())
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] # defaultdict d = collections.defaultdict(list) for k, v in s: d[k].append(v) # Use dict and setdefault g = {} for k, v in s: g.setdefault(k, []).append(v) # Use dict e = {} for k, v in s: e[k] = v ##list(d.items()) ##list(g.items()) ##list(e.items())
相关文章推荐
- Python的禅,“提姆彼得斯”说的非常有道理道出了这门编程语言的真谛!
- Python学习笔记(三)Python的list和tuple
- python 静态成员变量
- python函数——编码问题——str与Unicode的区别
- 01python初识—编辑器&版本&变量知识
- Python学习笔记(四)Python函数的参数
- Python关键字总结
- 通过抓包获取跳转url并通过dnspython模块查询监控服务是否正常
- Python学习:Flask框架和jinja2模板
- bat调用python命令
- numpy.zeros(shape, dtype=float, order='C')
- numpy.ones(shape, dtype=None, order='C')
- Python 正则表达式的剖析
- python3安装Fabric模块
- python glob使用
- leetcode @python 120. Triangle
- 重装python idle打不开解决方案
- leetcode @python 119. Pascal's Triangle II
- python2.7:str unicode 详解
- leetcode @python 118. Pascal's Triangle