python相同key合并value_python dicts列表如何合并key:value其中的值相同?

尽量避免复杂的嵌套数据结构。我相信人们倾向于

只有在他们密集使用数据结构的时候才能对他们进行摸索。之后

程序完成,或者暂时搁置,数据结构迅速

变得神秘。

对象可以用来以更理智、更有组织的方式保留甚至增加数据结构的丰富性。例如,看起来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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值