zoukankan      html  css  js  c++  java
  • set和dict

    dict属于mapping类型

    from collections.abc import Mapping,MutableMapping
    from collections.abc import __all__
    
    # dict 属于Mapping类型
    
    a = {}
    print(isinstance(a,MutableMapping))

    copy 浅拷贝

    a = {
        "liming1":{"company":"tencent1"},
        "liming2":{"company":"tencent2"},
    }
    
    # clear
    """ D.clear() -> None.  Remove all items from D. """
    # a.clear()
    
    #copy 浅拷贝
    """ D.copy() -> a shallow copy of D """
    new_dict = a.copy()
    new_dict['liming1']['company'] = 'tencent3'
    
    print(a)
    print(new_dict)
    
    ###########
    {'liming1': {'company': 'tencent3'}, 'liming2': {'company': 'tencent2'}}
    {'liming1': {'company': 'tencent3'}, 'liming2': {'company': 'tencent2'}}

    fromkeys

    # fromkeys
    new_list = ['liming1','liming2']
    
    new_dict = dict.fromkeys(new_list,{'company':'tencent'})
    
    print(new_dict)

    update

    # update
    
    new_dict.update({'lisa':{"company":"tencent2"}})
    new_dict.update({'liming2':{"company":"tencent2"}})
    new_dict.update(jenny={'company':'beijing'})
    new_dict.update([('jenny',{'company':'shanghai'})])
    print(new_dict)

    defaultdict  

    __missing__ 很重要
    from collections import defaultdict
    import collections
    s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
    
    d = collections.defaultdict(list)
    for k, v in s:
        d[k].append(v)
    
    print(list(d.items()))
    
    s = 'mississippi'
    d = defaultdict(int)
    for k in s:
         d[k] += 1
    print(list(d.items()))#set 不可变集合 fronzenset  无序  不重复

     

    set和frozenset 的区别

    刚开始也讲了frozenset是不可变的,如果修改是报错的,那到底有什么用处呢
    应用场景:一般dict 的key 是不变的,我们就可以用
    那我们用代码证明下,set不会报错,frozenset 会报错.

    s = {'a','b'}
    s.add('c')
    print(s)
    
    f = frozenset('abcd')  # 可以作为dict的key
    print(f)
    
    # 向set添加数据
    another_set = set('fgh')
    
    s.update(another_set)
    print(s)

    difference 的用法

    # 先看方法描述吧 ( Return the difference of two or more sets as a new set.)
    # 用例子加深印象。
    a=set("abc")
    print(a.difference("bcd"))
    print(a)

    set集合运算(|,&,-)

    a=set("abc")
    b=set("bcd")
    print(a-b)   #对a进行去重
    print(a | b) #并集
    print(a & b) #交集
    
    # {'a'}
    # {'c', 'a', 'd', 'b'}
    # {'c', 'b'}
  • 相关阅读:
    python中类中的@property
    Python列表的三种遍历(序号和值)的方法
    Numpy一文全了解
    python中list操作方法
    Material Design
    android动画xml
    java配置opencv-在eclipse中
    android 重装sdk或者系统的时模拟器出现can open ****
    hdu acm 1005
    hdu acm 1007
  • 原文地址:https://www.cnblogs.com/richiewlq/p/11073272.html
Copyright © 2011-2022 走看看