zoukankan      html  css  js  c++  java
  • python 练习题

    按要求完成下列转化(如果给list3再添加多个类似的字典如{"name": "太白", "hobby": "sport"}而你的代码不能通用,则只能得4分)。(6分)
    list3 = [
    {"name": "alex", "hobby": "抽烟"},
    {"name": "alex", "hobby": "喝酒"},
    {"name": "alex", "hobby": "烫头"},
    {"name": "wusir", "hobby": "喊麦"},
    {"name": "wusir", "hobby": "街舞"},
    ]
    # 如何把上面的列表转换成下方的列表?
    list4 = [
    {"name": "alex", "hobby_list": ["抽烟", "喝酒", "烫头"]},
    {"name": "wusir", "hobby_list": ["喊麦", "街舞"]},

    user_list=[
            {"name": "alex", "hobby": "抽烟"},
            {"name": "alex", "hobby": "喝酒"},
            {"name": "alex", "hobby": "烫头"},
            {"name": "wusir", "hobby": "喊麦"},
            {"name": "wusir", "hobby": "街舞"},
            {"name": "alex", "hobby": "泡吧"},
            {"name":"太白", "hobby":"开车"}
             ]
    # [{"name": "alex", "hobby_list": ["抽烟","喝酒","烫头","泡吧"]},{"name": "wusir", "hobby_list": ["喊麦", "街舞"]},]
    
    result = [] # {'name': 'alex', 'hobby_list': ['抽烟']}
    for user in user_list:
        # 1.判断是否在result里面存在了这个人, 如果存在. 把hobby_list添加一个hobby
        # 2.不存在. 创建一个新字典
        for new_user in result:
            if user['name'] == new_user['name']:
                new_user['hobby_list'].append(user['hobby'])
                break
        else:
            dic = {}
            dic["name"] = user['name']
            dic['hobby_list'] = [user['hobby']]
            result.append(dic)
    print(result)
  • 相关阅读:
    NodeJS优缺点
    移动端触摸相关事件touch、tap、swipe
    vscode使用技巧
    js 字符串转数字
    js 导出Excel
    <!--[if IE 9]> <![endif]-->
    js 异步请求
    关于windows串口处理
    mfc 托盘提示信息添加
    微软的麦克风处理示列代码
  • 原文地址:https://www.cnblogs.com/beihan/p/9325414.html
Copyright © 2011-2022 走看看