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

    集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),
    但是集合本身是不可哈希的(所以集合做不了字典的键)的。

    以下是集合最重要的两点:

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

    (2)关系测试,测试两组数据之间的交集,差集,并集等关系。

    1. 集合的创建

    ```Python set1 = set({1, 2, "barry"}) set2 = {1, 2, "barry"} print(set1, set2) ``` 执行结果为: ```Python {'barry', 1, 2} {'barry', 1, 2} ```

    2. 集合的增

    2.1 add()

    ```Python set1 = {"a", "b", "c"} set1.add("d") print(set1) ``` 执行结果为: ```Python {'b', 'a', 'd', 'c'} ```

    2.1 update()

    update():迭代着增加 ```Python set1 = {"a", "b", "c"} set1.update("A") print(set1) set1.update("B") print(set1) set1.update([1, 2, 3]) print(set1) ``` 执行结果为: ```Python {'c', 'b', 'A', 'a'} {'A', 'a', 'B', 'c', 'b'} {1, 2, 3, 'A', 'a', 'B', 'c', 'b'} ```

    3. 集合的删

    ```Python set1 = {"a", "b", "c", "d", "e"} set1.remove("a") #删除一个元素 print(set1)

    set1.pop() #随机删除一个元素
    print(set1)

    set1.clear() #清空集合
    print(set1)

    del set1 #删除集合
    print(set1)

    
    <h2>4. 集合的其他操作</h2>
    <h3>4.1 交集(& 或者 intersection)</h3>
    ```Python
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 8}
    print(set1 & set2)              #{4, 5}
    print(set1.intersection(set2))  #{4, 5}
    

    4.2 并集(| 或者 union)

    ```Python set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 | set2) #{1, 2, 3, 4, 5, 6, 7, 8} print(set2.union(set1)) #{1, 2, 3, 4, 5, 6, 7, 8} ```

    4.3 差集(- 或者 differene)

    ```Python set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 - set2) #{1, 2, 3} print(set1.difference(set2)) #{1, 2, 3} ```

    4.4 反交集(^ 或者 symmetric_difference)

    ```Python set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 ^ set2) #{1, 2, 3, 6, 7, 8} print(set1.symmetric_difference(set2)) #{1, 2, 3, 6, 7, 8} ```

    4.5 子集与超集

    ```Python set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5, 6}

    print(set1 < set2) #True
    print(set1.issubset(set2)) #True

    这两个相同,都是说明set1是set2子集

    print(set2 > set1) #True
    print(set2.issuperset(set1))#True

    这两个相同,都是说明set2是set1超集

    <h2>5. frozenset不可变集合,让集合变成不可变类型</h2>
    ```Python
    s = frozenset("barry")
    print(s, type(s))   
    

    执行结果为:

    frozenset({'b', 'a', 'r', 'y'}) <class 'frozenset'>
    
  • 相关阅读:
    Linux搭建NFS提供磁盘给Windows使用
    Linux shell实现Mysql异地备份数据库
    Linux使用Shell脚本实现ftp的自动上传下载
    双绞线的制作(常用568B)
    网络硬件设备(职高高考笔记)
    USB-Redirector-Technician 永久破解版(USB设备映射软件)
    LG的nexus5(32GB版本
    关于sql注入的简要演示
    什么是汇编语言?(简要介绍)
    WebLogic “Java 反序列化”过程远程命令执行
  • 原文地址:https://www.cnblogs.com/yang-wei/p/9630535.html
Copyright © 2011-2022 走看看