zoukankan      html  css  js  c++  java
  • python 集合 set

     
    python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。
     
    set 的创建 

    • 使用set()函数创建
    >>> set()  #new empty set object
    set()
    >>> set([1,2,3,3,4])  #new set object
    {1, 2, 3, 4}
    >>> set("Hello World")  
    {'e', 'H', 'r', ' ', 'd', 'l', 'o', 'W'}
    • 使用{}创建
    >>> {1,2,3,3,4}
    {1, 2, 3, 4}

    set 的基本操作


    • 标准数学操作 ----并集、交集、差集和对称差集
    • >>> s = set([1,2,3,3])
      >>> t = set([3,4,4,5])
      >>> s|t                 # t 和 s的并集      
      {1, 2, 3, 4, 5}       
      >>> s&t                 # t 和 s的交集  
      {3}
      >>> t-s                 # 求差集(项在t中,但不在s中)  
      {4, 5}
      >>> t^s                 # 对称差集(项在t或s中,但不会同时出现在二者中)
      {1, 2, 4, 5}
    • 添加,删除,清空操作
      1. add 函数  
        >>> t = set([1,2,3,3])
         # Add an element to a set
         #仅添加一项,添加list,或几项都会报错
        >>> t.add('x')               #添加一个字符
        >>> t.add("Hello")           #添加一个字符串
        >>> t.add(8)                 #添加一个数值
        >>> t
        {1, 2, 3, 8, 'x', 'Hello'}
      2. remove 函数    -----删除一项,在set中不存在就好引发keyError
        #Remove an element from a set;
        >>> t = set([1,2,3,'H','E'])
        >>> t
        {1, 2, 3, 'E', 'H'}
        >>> t.remove(3)
        >>> t
        {1, 2, 'E', 'H'}
        #t.remove(5)会报错
      3. discard函数   ---删除一项,在set中不存在也不好引发错误
        >>> t = set([1,2,2,3,'H','E'])
        >>> t.discard(2)
        >>> t
        {1, 3, 'E', 'H'}
        >>> t.discard(9)
        >>> t
        {1, 3, 'E', 'H'}
      4. update函数
        #Update a set with the union of itself and others
        #可以实现添加多项,如list
        >>> t = set([1,2,3,3])
        >>> t.update([3,4,5,5])
        >>> t
        {1, 2, 3, 4, 5}
      5. clear 函数
        #Remove all elements from this set.
        >>> t = set([1,2,3,3])
        >>> t.clear()
        >>> t
        set()
    • 其他基本操作
    1. copy函数 ---- 返回集合的浅复制
      >>> s = {3,3,4,4}
      >>> c = s.copy()
      >>> c.add(5)
      >>> c
      {3, 4, 5}
      >>> s
      {3, 4}
    2. len()函数 ----返回set的长度
      >>> s = {3,3,4,4}
      >>> s
      {3, 4}
      >>> len(s)
      2
    3. in 函数  --可以构造set的遍历,在海量数据去重复中可以考虑使用set,比hash快多了。
      >>> s = set([11,22,33,11,33,55])
      >>> s
      {33, 11, 22, 55}
      >>> c = [i for i in s]
      >>> c
      [33, 11, 22, 55]

      

  • 相关阅读:
    Linux的学习--系统目录
    PHP内核的学习--创建PHP扩展
    PHP的学习--连接MySQL的三种方式
    MIME Type
    颜色的命名
    JavaScript的学习--生成二维码
    MySQL的学习--触发器
    Google Guava之--cache
    java代码调用oracle存储过程
    oracle序列
  • 原文地址:https://www.cnblogs.com/qianwen/p/4112750.html
Copyright © 2011-2022 走看看