zoukankan      html  css  js  c++  java
  • Python之集合

    一、概念

    定义一个空的集合:

    jihe=set()    #定义一个空的集合
    • 集合也是一种数据类型,跟int  float list str dict tuple boolean一样。
    • 集合,天生可以去重
    l=[1,1,2,2,3,3]
    res=set(l)
    print(res) #结果为:{1,2,3}
    • 集合是无序的,跟字典一样,不能通过下标取值,也不能排序,如果想要排序,可以转成列表:
    l=list(res)

    二、取集合的方式

    xingneng=['tanailing','杨帆','liurongxin','小黑']
    zdh=['tanailing','杨帆','liurongxin','小军','海龙']
    
    #类型转换,列表转成集合:
    xingneng=set(xingneng)
    zdh=set(zdh)

    1、取交集

    方式一:     .intersection()方法;

    方式二:      一个 & 符。

    res=xingneng.intersection(zdh)  #取交集  方式一
    res=xingneng & zdh              #取交集  方式二
    print(res)

    2、取并集

    即:把2个集合合并到一起,然后去重。
    方式一:    .union()方法;

    方式二:     一个 | 符。

    res=xingneng.union(zdh) #取并集的方式一
    res=xingneng | zdh     #取并集的方式二

    3、取差集

    集合A的差集=集合A - 集合A∩集合B

    方式一:   .difference()方法;

    方式二: 一个 - 符。

    res=xingneng.difference(zdh) #取差集的方式一
    res=xingneng - zdh          #取差集的方式二

    4、取对称差集

    即:取两个集合里面不重复的值。

    方式一:  .symmetric_difference()方法;

    方式二:   一个^符。

    res=xingneng.symmetric_difference(zdh) #取对称差集的方式一
    res=xingneng ^ zdh              #取对称差集的方式二

    三、集合的判断方式

    • 子集与父集

    import string #导入字符串模块
    l1=set(string.ascii_lowercase) #取所有小写字母,并存成集合
    l2={'a','b','c'}

    可以看到,l2是l1的子集,l1是l2的父集。

    1、判断A是否是B的子集

    使用A.issubset(B)方法:

    print(l2.issubset(l1) #结果:True

    2、判断A是否是B的子集

    使用A.issuperset(B)方法:

    print(l1.issuperset(l2) #结果为True

    3、判断A与B是否无交集

    使用.isdisjoint()方法:

    print(l1.isdisjoint(l2) #结果:False

    四、集合的使用方式

    1、集合中加元素

    使用.add()方法:

    l2.add('s')

    2、集合中删除指定元素

    使用.remove()方法:

    l2.remove('a')

    3、集合中随机删除元素

    使用.pop()方法:

    l2.pop()

    4、循环

    集合也可以循环:

    for l in l1:
        print(l)
    每天进步一点点,快乐生活多一点。
  • 相关阅读:
    python 报错:reduce failed to synchronize: device-side assert triggered
    pytorch 分割二分类的两种形式
    Leetcode 104. 二叉树的最大深度
    LeetCode 78. 子集
    python报错:1only batches of spatial targets supported (non-empty 3D tensors) but got targets of size
    PyTorch:The "freeze_support()" line can be omitted if the program is not going to be frozen
    pytorch创建tensor的四种方法
    Leetcode 四数之和
    C++的类和对象
    结构体
  • 原文地址:https://www.cnblogs.com/yiruliu/p/9649469.html
Copyright © 2011-2022 走看看