代码:
def main():
persons = [{"user_id":2009, "name":"zpf", "sex":"man"}
,{"user_id":2010, "name":"ly","sex":"man"}
,{"user_id":2009,"name":"lc","age":22}
,{"user_id":2009,"name":"yw","birthday":199010}
,{"user_id":2010,"age":25,"num":201010603211}
,{"user_id":2011,"name":"dl","age":26}
,{"user_id":2012,"name":"zpf","age":22}]
ids = []
person_list = []
for person in persons:
id = person["user_id"]
temp = {}
if id not in ids:
ids.append(id)
temp_list = filter(lambda x: x["user_id"]==person["user_id"], persons)
for i in temp_list:
temp.update(i)
person_list.append(temp)
else:
continue
return person_list
需求:合并人员列表中user_id相同的dict到一个dict中
结果:
[{‘user_id‘: 2009, ‘birthday‘: 19901020, ‘name‘: ‘yw‘, ‘age‘: 22, ‘sex‘: ‘man‘},
{‘user_id‘: 2010, ‘num‘: 201010603211, ‘name‘: ‘ly‘, ‘age‘: 25, ‘sex‘: ‘man‘},
{‘user_id‘: 2011, ‘age‘: 26, ‘name‘: ‘dl‘},
{‘user_id‘: 2012, ‘age‘: 22, ‘name‘: ‘zpf‘}]
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-07 10:08:10