• python数据类型(集合)


    一、集合概念

      集合是一个数学概念:由一个或多个确定的元素所构成的整体叫做集合。
      集合中的元素三个特征

    1. 确定性(元素必须可hash)
    2. 互异性(去重)——将一个列表变为集合,就自动去重了
    3. 无序性(集合中的元素没有先后之分),如集合{3,4,5}和{3,5,4}算作同一个集合。

     注意:集合的主要作用是去重和关系运算

    二、集合关系运算

      关系运算:两组数据间的交集、差集、并集等关系。

    • in,not in:判断某元素是否在集合内
    • ==,!=:判断两个集合是否相等

      两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

    set.isdisjoint(s)     # 判断两个集合是不是不相交
    set.issuperset(s)     # 判断集合是不是包含其他集合,等同于a>=b
    set.issubset(s)       # 判断集合是不是被其他集合包含,等同于a<=b

      集合创建及关系运算

    s = {1,2,3,2,4,5} # 创建集合
    s = set([1,3,4,5,6]) # 转化为集合
    
    iphone7 = {'alex','rain','jack','old_driver'}
    iphone8 = {'alex','shanshan','jack','old_boy'}
    
    # 交集
    iphone7.intersection(iphone8)
    # 交集
    iphone7 & iphone8
    
    # 差集
    iphone7.difference(iphone8) # iphone7有iphone8没有的
    # 差集
    iphone7 - iphone8
    
    # 并集(去重)
    iphone7.union(iphone8)
    # 并集
    iphone8 | iphone7   # 管道符
    
    # 对称差集(只买了iPhone7 or iphone8的人)
    iphone8.symmetric_difference(iphone7)
    # 对称差集
    iphone7 ^ iphone8

    三、集合操作

    '''
    单个元素的增加 : add(),add的作用类似列表中的append
    对序列的增加 : update(),而update类似extend方法,update方法可以支持同时传入多个参数:
    '''
    >>> a={1,2}
    >>> a.update([3,4],[1,2,7])
    >>> a
    {1, 2, 3, 4, 7}
    >>> a.update("hello")
    >>> a
    {1, 2, 3, 4, 7, 'h', 'e', 'l', 'o'}
    >>> a.add("hello")
    >>> a
    {1, 2, 3, 4, 'hello', 7, 'h', 'e', 'l', 'o'}
    
    '''
    元素的删除
    集合删除单个元素有两种方法:
    元素不在原集合中时:
    set.discard(x)不会抛出异常
    set.remove(x)会抛出KeyError错误
    >>> a={1,2,3,4}
    '''
    >>> a={1,2,3,4}
    >>> a.discard(1)
    >>> a
    {2, 3, 4}
    >>> a.discard(1)
    >>> a
    {2, 3, 4}
    >>> a.remove(1)
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 1
    
    '''
    pop():由于集合是无序的,pop返回的结果不能确定,且当集合为空时调用pop会抛出KeyError错误,
    clear():清空集合
    '''
    >>> a={3,"a",2.1,1}
    >>> a.pop()
    >>> a.pop()
    >>> a.clear()
    >>> a
    set()
    >>> a.pop()
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 'pop from an empty set'
  • 相关阅读:
    Enum, Generic and Templates
    Writing A Threadpool in Rust
    A First Look at Rust Language
    Closures in OOC
    Complexity Behind Closure
    Introduction to OOC Programming Language
    OOC,泛型,糟糕的设计。
    Enlightenment笔记
    Machine Learning/Random Projection
    Machine Learning/Introducing Logistic Function
  • 原文地址:https://www.cnblogs.com/xiugeng/p/8546894.html
Copyright © 2020-2023  润新知