zoukankan      html  css  js  c++  java
  • 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'}
    
    

  • 相关阅读:
    LeetCode--Sudoku Solver
    LeetCode--Merge Intervals
    LeetCode--Valid Number
    LeetCode--Max Points on a Line
    1.1
    智能指针原理与简单实现(转)
    C++内存管理(转)
    算法题--扔棋子
    LeetCode--Substring with Concatenation of All Words
    线性代数与MATALB1
  • 原文地址:https://www.cnblogs.com/wenyule/p/8926871.html
Copyright © 2011-2022 走看看