• Python集合详解


    一、集合的定义和基本操作方法

    1、定义

    • 不同元素组成(会自动去掉重复的元素)
    • 无序
    • 集合中的元素必须是不可变类型

    2、集合的格式举例

      x = {1,2,5,"hello","word"}

    3、集合的基本操作

      1)不同类型转变为集合的方法举例

        x = set("hello")          #转变为普通可变集合

        x = set(["hello","hello","word"])    #转变为普通可变集合

        x = frozenset("hello")             #转变为特殊不可变集合

    2)增加集合的元素

    x = {1,2,3,5}

    x.add("y")

    3)清除集合

    x = {1,2,3,5}

    x.clear()

    4)复制集合

    x = {1,2,3,5}

    x1 = x.copy()

    5)随机删除集合元素

    x = {1,2,3,5}

    x.pop()

    6)指定删除集合元素,没找到要删除的元素时会报错

    x = {1,2,3,5}

    x.remove(5)

    7)指定删除集合元素,没找到要删除的元素时不会报错

    x = {1,2,3,5}

    x.discard(8)

    8)求交集

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.intersection(B1))
    print(A1 & B1)

    9)求并集

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.union(B1))
    print(A1 | B1)

    10)求差集

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.difference(B1)) #A1-B1的差集
    print(A1 - B1)
    print(B1.difference(A1)) #B1-A1的差集
    print(B1 - A1)

    11)求交叉补集

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.symmetric_difference(B1))
    print(A1 ^ B1)

    备注:symmetric_difference_update  是求交叉补集并复制给原值,例如将A1和B1的交叉补集复制给A1,此处省略;

    12)将A1和B1的差集赋值给A1

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    A1.difference_update(B1)    #相当于 A1 = A1 - B1
    print(A1)

    13)将A1和B1的交集复制给A1

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    A1.intersection_update(B1) #相当于 A1 = A1 & B1
    print(A1)

    14)有交集返回True,无交集返回False

    A = ['a','b','c','d']
    B = ['a','b','e']
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.isdisjoint(B1))

    15)判断A1是否是是B1的子集,即A1 <= B1成立则显示True,否则显示False

    A = [1,2,3]
    B = [1,2,3,4,5]
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.issubset(B1))

    16)判断A1是否是是B1的父集,即A1 >= B1成立则显示True,否则显示False

    A = [1,2,3,4,5]
    B = [1,2,3,4,5]
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    print(A1.issuperset(B1))

    17)将B1的多个值增加到A1

    A = [1,2,3,4,5]
    B = [1,2,3,4,5]
    A1 = set(A)
    B1 = set(B)
    print(A1,B1)
    A1.update(B1)
    print(A1)

    备注:与add相比的区别,add一次只能增加一个值,update一次可以增加多个值;

    18)使用集合对列表进行去重(不考虑列表内容的顺序) 

    x = ["a","b","a","a"]
    x = list(set(x))

     

     

     

  • 相关阅读:
    关于 __bridge
    关于loadView
    关于ViewDidUnload
    55. Jump Game(中等)
    54. Spiral Matrix(中等)
    48. Rotate Image(中等)
    34. Search for a Range
    18. 4Sum(中等)
    16. 3Sum Closest(中等)
    41. First Missing Positive(困难, 用到 counting sort 方法)
  • 原文地址:https://www.cnblogs.com/wangzengyi/p/12119868.html
Copyright © 2020-2023  润新知