鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 编程语言开发 > python > >

Python容器小技巧

来源:互联网 作者:佚名 时间:2013-10-28 10:29
Python容器小技巧 operator 6 import collections Person(object): (self, name, age = 0): 10 self.name = name 11 self.age = age (self): \ % (self.name, self.age) testListSort(): persons = [Person(name) , , )] p )): , p.name 24 25 sm_p = Person

Python容器小技巧

operator 6 import collections Person(object): (self, name, age = 0): 10 self.name = name 11 self.age = age (self): \ % (self.name, self.age) testListSort(): persons = [Person(name) , , )] p )): , p.name 24 25 sm_p = Person(27) , operator.attrgetter()(sm_p) : )(sm_p) 32 except AttributeError: testDictGroup(): , age) for age in (78, 14, 78, 42, 14)] 37 persons_by_age = {} 38 for p in persons: p.age not in persons_by_age: 41 persons_by_age[p.age] = [p] 42 else: 43 persons_by_age[p.age].append(p) age in persons_by_age: % age 48 for p in persons_by_age[age]: 49 print p testDictGroup_Adv(): , age) for age in (78, 14, 78, 42, 14)] persons_by_age = collections.defaultdict(list) 57 for p in persons: 58 persons_by_age[p.age].append(p) age in persons_by_age: % age 63 for p in persons_by_age[age]: 64 print p testListEmpty(): 67 persons = [] 68 if persons: len(persons) 71 else: == : 75 testDictGroup_Adv() 76 testListEmpty()

主要参考

posted on

网友评论
<