python 集合

发布时间:2018-02-24 17:21:10编辑:admin阅读(3338)

    集合是一个无序的,不重复的数据组合,它的主要作用如下:


    去重,把一个列表变成集合,就自动去重了

    关系测试,测试两组数据之前的交集、差集、并集等关系


    去重

    将列表转换为集合

    使用set()方法

    list_1 = [1,2,4,5,2,6,7,4,8]
    list_1 = set(list_1)
    print(list_1,type(list_1))

    执行输出

    {1, 2, 4, 5, 6, 7, 8}

    结果有点像字典的格式,但它不是字典,是一个集合。里面数据,已经去重了。

    集合和字典一样,也是无序的。


    交集

    使用intersection()方法,将2个数据相同的部分提取出来

    list_1 = [1,2,4,5,2,6,7,4,8]
    list_1 = set(list_1)
    list_2 = set([2,55,46,91,4,8])
    print(list_1.intersection(list_2))

    执行输出

    {8, 2, 4}


    并集

    使用union()方法,将2个数据合并,去除重复的元素

    list_1 = [1,2,4,5,2,6,7,4,8]
    list_1 = set(list_1)
    list_2 = set([2,55,46,91,4,8])
    print(list_1.union(list_2))

    执行输出

    {1, 2, 4, 5, 6, 7, 8, 46, 55, 91}


    差集

    我有,你没有的部分

    list_1 = [1,2,4,5,2,6,7,4,8]
    list_1 = set(list_1)
    list_2 = set([2,55,46,91,4,8])
    print(list_1.difference(list_2))

    执行输出

    {1, 5, 6, 7}

    说明: 拿list_1每一个元素去list_2中查找,如果有,直接忽略,否则就直接输出。


    也可以反过来,用list_2向list_1求差集

    print(list_2.difference(list_1))

    执行输出

    {91, 46, 55}


    子集

    子集是一个数学概念:如果集合A的任意一个元素都是集合B的元素,那么集合A称为集合B的子集。

    也就是说,A集合的所有元素都包含在B集合中,A就是B的子集

    print(list_2.issubset(list_1))

    执行输出 False


    超集

    超集定义:如果一个集合S2中的每一个元素都在集合S1中,且集合S1中可能包含S2中没有的元素,则集合S1就是S2的一个超集。

    #判断list_2是否是1的超集
    print(list_2.issuperset(list_1))

    执行输出 False


    对称差集

    将2个集合合并,删除相同的元素。

    print(list_1.symmetric_difference(list_2))

    执行输出

    {1, 7, 5, 6, 55, 91, 46}


    判断是否是相交集,返回bool值

    list_1 = [1,2,4,5,2,6,7,4,8]
    list_1 = set(list_1)
    list_2 = set([2,55,46,91,4,8])
    list_3 = set([3,9,10])
    print(list_3.isdisjoint(list_2))

    执行输出 True

    集合3中的每一个元素,在集合2中,一个都没找到,返回True,否则返回false

    哪怕只有一个元素找到了,也会返回false


    上面的集合关系比较,都是用英文字母方法做的,也可以用符号表示


    交集

    print(list_1 & list_2)

    执行输出

    {8, 2, 4}


    并集

    print(list_1 | list_2)

    执行输出

    {1, 2, 4, 5, 6, 7, 8, 46, 55, 91}


    差集

    print(list_1 - list_2)

    执行输出

    {1, 5, 6, 7}


    对称差集

    print(list_1 ^ list_2)

    执行输出

    {1, 7, 5, 6, 55, 91, 46}


    基本操作


    添加

    list_1.add(999)
    print(list_1)

    执行输出

    {1, 2, 4, 5, 6, 7, 8, 999}


    添加多个

    list_1.update([88,77,66])

    执行输出

    {1, 2, 66, 4, 5, 6, 7, 8, 77, 88}


    删除

    list_1.remove(2)
    print(list_1)

    执行输出

    {1, 4, 5, 6, 7, 8}


    问题来了,集合里面有2个数字2,该删除哪一个呢?

    集合天生就是去重的,所以不存在这个问题,它里面的每一个值都是唯一的。


    集合的长度

    print(len(list_1))

    执行输出 7


    判断某个值是否存在集合中

    print(1 in list_1)

    执行输出 True


    判断某个值不存在集合中

    print(1 not in list_1)

    执行输出 False


    列表,字典,集合,字符串 都可以用in方法


    随机删除并返回删除的元素

    print(list_2.pop())

    执行输出 2


    删除一个不存在的数据

    print(list_1.discard(888))

    执行输出 None

    为什么会返回 None 呢?因为discard()没有返回值,即使删除一个不存在的值,也不会报错

    而remove()删除一个不存在的值,会报错。


关键字

上一篇: python 三级菜单

下一篇: python 文件操作