python dict使用技巧,pythondict,在 Dictionary
python dict使用技巧,pythondict,在 Dictionary
在 Dictionary 中元素分组
和上面类似,先创建 Persons:
class Person(object): def __init__(self, age): self.age = agepersons = [Person(age) for age in (78, 14, 78, 42, 14)]
如果现在我们要按照年龄分组的话,一种方法是使用 in 操作符:
persons_by_age = {}for person in persons: age = person.age if age in persons_by_age: persons_by_age[age].append(person) else: persons_by_age[age] = [person]assert len(persons_by_age[78]) == 2
相比较之下,使用 collections 模块中 defaultdict 方法的途径可读性更好:
from collections import defaultdictpersons_by_age = defaultdict(list)for person in persons: persons_by_age[person.age].append(person)
defaultdict 将会利用接受的参数为每个不存在的 key 创建对应的值,这里我们传递的是 list,所以它将为每个 key 创建一个 list 类型的值。
相关内容
- Python统计列表中元素出现的次数,python统计列表元素
- Python yield使用示例,pythonyield示例,下面2段代码通过Py
- python使用eval,exec将字符串(string)转为字典(dict),pythone
- Python POP3 收取邮件,pythonpop3,python 为我们提供
- python爬虫抓网页的总结,python爬虫抓,学用python也有3个
- python核心模块之pickle和cPickle的使用示例,picklecpickle,
- Python使用ConfigParser读写ini配置文件,,ini文件格式概述
- Python读取纯真IP数据库,pythonip数据库,纯真IP数据库可谓
- python求两序列的和最小差值序列,python最小差值序列
- python实现Bogo排序算法,pythonbogo排序,Bogo算法定义下面是
评论关闭