例:
user_list = [{"name":"alex","hobby":"抽烟"}, {"name":"alex","hobby":"喝酒"}, {"name":"alex","hobby":"烫头"}, {"name":"wusir","hobby":"喊麦"}, {"name":"wusir","hobby":"街舞"}]==>[{‘name‘: ‘alex‘, ‘hobby_list‘: [‘抽烟‘, ‘喝酒‘, ‘烫头‘]}, {‘name‘: ‘wusir‘, ‘hobby_list‘: [‘喊麦‘, ‘街舞‘]}]
解题思路: 判断是否在result里面存在这个人的信息,如果不存在则新建一个字典,把hobby_list对应的value值放到一个列表中; 如果存在把hobby_list对应的列表加入一个hobby.
解题步骤:
user_list = [{"name":"alex","hobby":"抽烟"}, {"name":"alex","hobby":"喝酒"}, {"name":"alex","hobby":"烫头"}, {"name":"wusir","hobby":"喊麦"}, {"name":"wusir","hobby":"街舞"}]result = []for user in user_list: for new_user in result: if new_user["name"] == user["name"]: new_user.setdefault("hobby_list",[]).append(user["hobby"]) break else: dic = {} dic["name"] = user["name"] dic["hobby_list"] = [user["hobby"]] result.append(dic)print(result)
如果默认值参数是一个可变的数据类型,在调用的时候改变了.在其他位置看到的也跟着改变.
例:
def extendList(val, list=[]): list.append(val) return listlist1 = extendList(10)list2 = extendList(123, [])list3 = extendList(‘a‘)print(‘list1=%s‘ % list1)print(‘list2=%s‘ % list2)print(‘list3=%s‘ % list3)==>list1=[10, ‘a‘] list2=[123] list3=[10, ‘a‘]
原文地址:https://www.cnblogs.com/gxj742/p/9325418.html
时间: 2024-10-08 17:40:24