• 数据集之集合


    特征

    1.确定性(元素必须可hash)
    2.互异性(去重)
    3.无序性(集合中的元素没有顺序,先后之分)

     1 >>> s = {1,1,1,2,2,3,4,5,6,7}    # 创建
     2 >>> s
     3 {1, 2, 3, 4, 5, 6, 7}
     4 >>> s.add(2)                    # 添加,重复添加也添加不上
     5 >>> s.add(22)
     6 >>> s
     7 {1, 2, 3, 4, 5, 6, 7, 22}
     8 >>> s.update([11,33,44])        # 添加批量元素
     9 >>> s
    10 {1, 2, 3, 4, 5, 6, 7, 33, 11, 44, 22}
    11 >>> s.discard(7)                # 删除指定元素
    12 >>> s.pop()                        # 删除随机元素,pop()没有参数
    13 1
    14 >>> s.pop(2)
    15 Traceback (most recent call last):
    16   File "<pyshell#14>", line 1, in <module>
    17     s.pop(2)
    18 TypeError: pop() takes no arguments (1 given)
    19 >>> s.clear()                    # 清空集合
    20 >>> s
    21 set()
    22 >>> s.add(1)
    23 >>> s.copy()                    # 复制
    24 {1}
    25 >>> s.update([11,33,44])
    26 >>> s
    27 {1, 11, 44, 33}
    28 >>> s.copy()
    29 {1, 11, 44, 33}
    30 >>> s.add([12,13,14])            # 不能添加非 hash 元素
    31 Traceback (most recent call last):
    32   File "<pyshell#22>", line 1, in <module>
    33     s.add([12,13,14])
    34 TypeError: unhashable type: 'list'
    35 >>>

    集合关系测试

    >>> stu1 = {'python','linux','html','mysql'}
    >>> stu2 = {'linux','python','go','css','javascript'}
    >>> stu1.intersection(stu2)            # 交集,两个集合都有的
    {'python', 'linux'}
    >>> stu1 & stu2
    {'python', 'linux'}
    >>> stu1.difference(stu2)            # 差集,除了都有的,比后者不同的部分就是差集
    {'mysql', 'html'}
    >>> stu1 - stu2                        # 相同的,负的都去掉,剩下的是差集
    {'mysql', 'html'}
    >>> stu2 - stu1                        # 前者不同于后者的部分
    {'javascript', 'go', 'css'}
    
    
    >>> stu1.union(stu2)                # 并集,合并两者所有的
    {'linux', 'javascript', 'html', 'mysql', 'python', 'go', 'css'}
    >>> stu2 | stu1
    {'linux', 'javascript', 'python', 'go', 'css', 'html', 'mysql'}
    
    
    >>> stu1.symmetric_difference(stu2)            # 对称差集,并集去掉交集
    {'javascript', 'go', 'css', 'html', 'mysql'}
    >>> stu2 ^ stu1
    {'javascript', 'html', 'mysql', 'go', 'css'}
    
    
    >>> stu1.difference_update(stu2)                # 将差集,赋给 stu1     同理交集也可以
    >>> stu1
    {'html', 'mysql'}
    View Code

    <wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">





  • 相关阅读:
    idea maven install java: 程序包不存在
    Window10取消文件默认打开方式
    @ModelAttribute与@RequestBody的区别
    python小知识
    CentOS下yum方式安装FFmpeg
    推荐一款可以直接下载浏览器sources资源的Chrome插件
    如何在python中使用Elasticsearch
    python logging模块“另一个程序正在使用此文件,进程无法访问。”问题解决办法
    Python的伪造数据生成器:Faker
    docker修改系统时间总结
  • 原文地址:https://www.cnblogs.com/wenyule/p/7485e600caa469187b38aaba87c255ef.html
Copyright © 2020-2023  润新知