• python的6种基本数据类型--集合


    特征

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

    >>> s = {1,1,1,2,2,3,4,5,6,7}    # 创建
    >>> s
    {1, 2, 3, 4, 5, 6, 7}
    >>> s.add(2)                    # 添加,重复添加也添加不上
    >>> s.add(22)
    >>> s
    {1, 2, 3, 4, 5, 6, 7, 22}
    >>> s.update([11,33,44])        # 添加批量元素
    >>> s
    {1, 2, 3, 4, 5, 6, 7, 33, 11, 44, 22}
    >>> s.discard(7)                # 删除指定元素
    >>> s.pop()                        # 删除随机元素,pop()没有参数
    1
    >>> s.pop(2)
    Traceback (most recent call last):
      File "<pyshell#14>", line 1, in <module>
        s.pop(2)
    TypeError: pop() takes no arguments (1 given)
    >>> s.clear()                    # 清空集合
    >>> s
    set()
    >>> s.add(1)
    >>> s.copy()                    # 复制
    {1}
    >>> s.update([11,33,44])
    >>> s
    {1, 11, 44, 33}
    >>> s.copy()
    {1, 11, 44, 33}
    >>> s.add([12,13,14])            # 不能添加非 hash 元素
    Traceback (most recent call last):
      File "<pyshell#22>", line 1, in <module>
        s.add([12,13,14])
    TypeError: unhashable type: 'list'
    >>>
    

    集合关系测试

    >>> 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'}
    
    

  • 相关阅读:
    2019-2020-1学期20192401《网络空间安全专业导论》第一周学习总结
    14201771010119穷吉
    13201771010119穷吉
    12穷吉201771010119
    11201771010119穷吉
    实验10穷吉201771010119
    实验九201771010119穷吉
    201771010119穷吉第八周
    七次201771010119穷吉
    实验六20177101010119穷吉
  • 原文地址:https://www.cnblogs.com/wenyule/p/8926871.html
Copyright © 2020-2023  润新知