尽量避免复杂的嵌套数据结构。我相信人们倾向于
只有在他们密集使用数据结构的时候才能对他们进行摸索。之后
程序完成,或者暂时搁置,数据结构迅速
变得神秘。
对象可以用来以更理智、更有组织的方式保留甚至增加数据结构的丰富性。例如,看起来item和price总是在一起的。因此,这两个数据最好在一个对象中配对:class Item(object):
def __init__(self,name,price):
self.name=name
self.price=price
类似地,一个人似乎有一个id和name和一套财产:class Person(object):
def __init__(self,id,name,*items):
self.id=id
self.name=name
self.items=set(items)
如果您接受使用此类类的想法,那么您的list_dicts可能会list_people = [
Person('001','jim',Item('pencil',0.99)),
Person('002','mary',Item('book',15.49)),
Person('002','mary',Item('tape',7.99)),
Person('003','john',Item('pen',3.49)),
Person('003','john',Item('stapler',9.49)),
Person('003','john',Item('scissors',12.99)),
]
然后,要基于id合并人员,可以使用Python的reduce函数,
与take_items一起,它从一个人那里获取(合并)项目并将其提供给另一个人:def take_items(person,other):
'''
person takes other's items.
Note however, that although person may be altered, other remains the same --
other does not lose its items.
'''
person.items.update(other.items)
return person
总而言之:import itertools
import operator
class Item(object):
def __init__(self,name,price):
self.name=name
self.price=price
def __str__(self):
return '{0} {1}'.format(self.name,self.price)
class Person(object):
def __init__(self,id,name,*items):
self.id=id
self.name=name
self.items=set(items)
def __str__(self):
return '{0} {1}: {2}'.format(self.id,self.name,map(str,self.items))
list_people = [
Person('001','jim',Item('pencil',0.99)),
Person('002','mary',Item('book',15.49)),
Person('002','mary',Item('tape',7.99)),
Person('003','john',Item('pen',3.49)),
Person('003','john',Item('stapler',9.49)),
Person('003','john',Item('scissors',12.99)),
]
def take_items(person,other):
'''
person takes other's items.
Note however, that although person may be altered, other remains the same --
other does not lose its items.
'''
person.items.update(other.items)
return person
list_people2 = [reduce(take_items,g)
for k,g in itertools.groupby(list_people, lambda person: person.id)]
for person in list_people2:
print(person)