zoukankan      html  css  js  c++  java
  • Python基础操作-集合

    Python set是基本数据类型的一种集合类型,它有可变集合(set())和不可变集合(frozenset)两种。创建集合set集合set添加集合删除交集并集差集的操作都是非常实用的方法。

    list_1 = set([1,3,5,7,5,8,10])

    list_2 = set([2,3,4,5,6,7,8])

    list_3 = set([1,3,5])

    一:基本操作

    添加一个add

    list_1.add(123)
    print(list_1)
    {1, 3, 5, 7, 8, 10, 123}

    添加多个update

    list_1.update([10,20,30,50])
    print(list_1)
    {1, 3, 5, 7, 8, 10, 50, 20 , 30}

    删除remove 如果删除集合内没有的则会报错

    list_1.remove(1)
    print(list_1)
    {3, 5, 7, 8, 10}

    list_1.remove(20)
    print(list_1)


    Traceback (most recent call last):
      File "D:/PyCharm/day1/集合测试.py", line 14, in <module>
        list_1.remove(20)
    KeyError: 20

    删除discard 如果删除集合内没有的不会报错

    list_1.discard(20)
    print(list_1)
    {1, 3, 5, 7, 8, 10}

    删除pop 随机删除一个成员

    list_1.pop()
    print(list_1)
    {3, 5, 7, 8, 10}

    二:关系测试

    交集

    print(list_1.intersection(list_2))

    {8, 3, 5, 7}

    并集

    print(list_1.union(list_2))

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

    差集

    print(list_1.difference(list_2))

    {1, 10}

    子集

    print(list_3.issubset(list_1))

    True

    父集

    print(list_1.issuperset(list_3))

    True

    对称差集

    print(list_1.symmetric_difference(list_2))

    {1, 2, 4, 6, 10}

  • 相关阅读:
    数学笔记目录
    机器学习笔记目录
    物理学笔记目录
    二阶递推公式的通项公式
    分析Analysis 笔记
    从傅里叶变换到小波变换
    电动力学 期末复习
    电动力学 期中复习
    热学 期中复习
    理论力学第一章 Lagrange方程
  • 原文地址:https://www.cnblogs.com/manger/p/7240130.html
Copyright © 2011-2022 走看看