1.题目

list3 = [
    {'name':'Alex','hobby':'抽烟'},
    {'name':'Alex', 'hobby':'喝酒'},
    {'name':'Alex', 'hobby':'烫头'},
    {'name':'Alex', 'hobby':'Massage'},
    {'name':'wusir', 'hobby':'喊麦'},
    {'name':'wusir', 'hobby':'街舞'},]
# 将以上列表转化成下列样式:
# list4 = [
#     {'name':'alex','hobby_list':['抽烟','喝酒','烫头','Message']},
#     {'name':'wusir','hobby_list':['喊麦','街舞']}]

2.解答

list4 = []
for i in list3:  # 循环list3, 得出每一个字典, ①
    # 第二次添加时候,判断i['name']在不在新建的字典里面  ,就要循环新形成的list4这个列表,找到name的对应值
    for j in list4:
        if j['name'] == i['name']:
            j['hobby_list'].append(i['hobby'])
            break
    else:
        dic = {}  # 建立一个新字典②
        dic['name'] = i['name']  # 将每个值赋值到新的字典里面③
        dic['hobby_list'] = [i['hobby']]  # 将每个值赋值到新的字典里面,这里是一个列表③
        list4.append(dic)  # 将字典添加到list4里面  ④
for ren in list3: # {"name": "alex", "hobby": "抽烟"},
    for el in list4:
        if el['name'] == ren['name']:
            el['hobby_list'].append(ren['hobby'])
            break
    else:
        dic = {}
        dic['name'] = ren['name']
        dic['hobby_list'] = [ren['hobby']]
        list4.append(dic) # 第一个人进去
print(list4)