• python 集合(set)基础


    1、定义

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    print(list_1,list_2)

      打印输出结果:

    {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}

    2、交集

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    
    print(  list_1.intersection(list_2) )
    print(list_1 & list_2)

      打印输出结果:

    {4, 6}
    {4, 6}

    3、并集

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    
    print(list_1.union(list_2))
    print(list_1 | list_2)

       打印输出结果:

    {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
    {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

    4、 差集 in list_1 but not in list_2

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    
    print(list_1.difference(list_2))
    print(list_1 - list_2)

      打印输出结果:

    {1, 3, 5, 7, 9}
    {1, 3, 5, 7, 9}

    5、差集 in list_2 but not in list_1

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    
    print(list_2.difference(list_1))
    print(list_2 - list_1)

      打印输出结果:

    {0, 2, 66, 8, 22}
    {0, 2, 66, 8, 22}

    6、子集

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_3 = set([1,3,7])
    
    print(list_3.issubset(list_1))

      打印输出结果:

    True

    7、超集

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_3 = set([1,3,7])
    
    print(list_1.issuperset(list_3))

      打印输出结果:

    True

    8、对称差集

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    list_2 =set([2,6,0,66,22,8,4])
    
    print(list_1.symmetric_difference(list_2))
    print(list_1 ^ list_2)

      打印输出结果:

    {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
    {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}

    9、判断是否有相同项,没有则返回true

    list_3 = set([1,3,7])
    list_4 = set([5,6,7,8])
    print(list_3.isdisjoint(list_4))

      打印输出结果:

    False

    10、add()与update

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    
    list_1.add(999)
    list_1.update([888, 777, 555])
    print(list_1)

       打印输出结果:

    {1, 3, 4, 5, 6, 7, 999, 9, 777, 555, 888}

    11、pop()

    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    
    print(list_1.pop())
    print(list_1.pop())
    print(list_1.pop())
    print(list_1.pop())
    print(list_1)

      打印输出结果:

    1
    3
    4
    5
    {6, 7, 9}

    12、discard()

    list_1 = [1,4,5,7,3,6,7,9,888]
    list_1 = set(list_1)
    
    print(  list_1.discard(888)  )
    print(list_1)

      打印输出结果:

    None
    {1, 3, 4, 5, 6, 7, 9}
  • 相关阅读:
    Windows:C:WindowsSystem32driversetchosts
    Quartz:Cron Expressions
    RabbitMQ:基本命令
    架构:一致性
    Javascript:自己写异步流程编程框架
    Python:Hello World级别的SimpleDb
    架构:互联网架构
    数据访问:三大范式
    数据访问:Implementing Efficient Transactions
    技术人生:special considerations that are very important
  • 原文地址:https://www.cnblogs.com/bad-robot/p/9679351.html
Copyright © 2020-2023  润新知