zoukankan      html  css  js  c++  java
  • python中字典,没键加键,有键操作其键对应的值,的思想

    cars = ['鲁A32444', '鲁B12333', '京B8989M', '黑C49678', '黑C46555', '沪B25041', '黑C34567']
    locations = {'': '上海', '': '北京', '': '黑龙江', '': '山东', '': '湖北', '': '湖南'}
    # 构建此数据类型{'山东': 2, '北京': 1, '黑龙江': 3, '上海': 1}
    
    # 方法一
    dic = {}
    for i in cars:
        if locations[i[0]] in dic:
            dic[locations[i[0]]] += 1
        else:
            dic[locations[i[0]]] = 1
    print(dic)
    
    # 方法二
    dic = {}
    for i in cars:
        # get方法,如果有键返回该键对应的值,如果没键,可以设置返回值
        dic[locations[i[0]]] = dic.get(locations[i[0]], 0) + 1
    print(dic)
    list3 = [
        {"name": "a", "hobby": "抽烟"},
        {"name": "a", "hobby": "喝酒"},
        {"name": "a", "hobby": "烫头"},
        {"name": "wu", "hobby": "喊麦"},
        {"name": "wu", "hobby": "街舞"},
    ]
    # 构建数据类型 list4 = [{"name": "a", "hobby_list": ["抽烟", "喝酒", "汤头"]}]
    # 思想:如果没键就添加键,如果有键就操作此键对应的值
    # 方法一
    list4 = []
    for i in list3:
        # print(i)
        for j in list4:
            if i['name'] == j['name']:  # i['name']='a'
                j['hobby_list'].append(i['hobby'])
                break
        else:
            list4.append({'name': i['name'], 'hobby_list': [i['hobby']]})
    print(list4)
    li = [11, 22, 33, 44, 55, 77, 88, 99, 90]
    # 构建数据类型{'key1': [11, 22, 33, 44, 55], 'key2': [77, 88, 99, 90]}
    # key1对应的小于60的值,key2对应大于60的值
    result = {}
    for i in li:
        if i < 66:
            if 'key1' not in result:
                result['key1'] = []
            result['key1'].append(i)
        else:
            if 'key2' not in result:
                result['key2'] = []
            result['key2'].append(i)
    print(result)
  • 相关阅读:
    ASP下的URL重写
    经典日历
    asp中使用存储过程
    带进度条的ASP无组件断点续传下载代码
    XML与ASP简单结合实现HTML模板功能
    ASP函数
    CSS垂直树形下拉列表
    ASP无组件上载,带进度条,多文件上载。。
    采用AJAX实现带进度条的文件上传
    Rose与PowerDesigner:两款建模工具对比分析比较
  • 原文地址:https://www.cnblogs.com/chen55555/p/10216900.html
Copyright © 2011-2022 走看看