集合类型

集合

  • 集合是一个不存在重复值且无序的数据类型

    • 集合是可hash类型 (hash就将值通过算法转换成绝对唯一的)

      • 不可变对象都是可hash类型

      • 可变对象都是不可hash类型

  • 集合的定义方式 (set{} 这里中括号不是在定义字典,而是集合,通过逗号分割多个值)

    >>>my_set = {1,2,3,4,5}
    >>>my_set
    {1, 2, 3, 4, 5}
  • 集合的常用方法

    # 通过dir函数查看一下
    >>> dir(set)
    ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
    View Code

    ​# 其他常用方法示例
    # add 添加单个元素
    >>>my_set = {1,2,3,4,5}
    >>>my_set.add(6)
    >>>my_set
    {1, 2, 3, 4, 5, 6}
    ​
    # update 可添加多个元素,列表,字典,字符串等等
    >>>my_set.update(['a','b','c'],{'name': 'dingh'},'boss')
    >>>my_set
    {1, 2, 3, 4, 5, 6, 's', 'a', 'o', 'b', 'name', 'c'}
    ​
    # pop 随机删除元素并返回,不需要传值
    >>>my_set = {1,2,3,4,5,6}
    >>>my_set.update(['a','b','c'],{'name': 'dingh'},'boos')
    >>>my_set
    {1, 2, 3, 4, 5, 6, 's', 'a', 'o', 'b', 'name', 'c'}
    ​
    # remove 删除元素不返回,元素不存在会报错
    >>>my_set.remove('name')
    >>>my_set
    {4, 5, 6, 's', 'a', 'o', 'b', 'c'}
    >>>my_set.remove('llll')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'llll
        
    # discard 同样是删除元素,元素不存在不会报错
    >>>my_set.discard('lll')
    >>>my_set.discard('c')
    >>>my_set
    {4, 5, 6, 's', 'a', 'o', 'b'}
    ​
    # clear 清空集合
    >>>my_set.clear()
    >>>my_set
    set()
    ​
    # copy 拷贝集合
    >>> set = {1,2,3}
    >>> set1 = set.copy()
    >>> set1
    {1, 2, 3}
    View Code

  • 集合运算

    >>>my_set = {'dingh','may','mahuat','wangjl'}
    >>>my_set2 = {'dingh','mahuat','wangjl','gaici'}
    # |合集 双方的所有元素去掉重复
    >>>my_set |my_set2
    {'dingh', 'wangjl', 'mahuat', 'gaici', 'may'}
    # &交集 双方都有的
    >>>my_set &my_set2
    {'dingh', 'wangjl', 'mahuat'}
    >>>my_set -my_set2 #my_set有而MySet2没有的
    {'may'}
    # -差集
    >>>my_set2 -my_set # MySe2有而MySet1没有的
    {'gaici'}
    # ^对称差集 # 去掉双方都有的
    >>>my_set ^my_set2
    {'gaici', 'may'}
    
posted @ 2018-10-25 21:16  浩小白  Views(97)  Comments(0Edit  收藏  举报