• python集合set与frozenset介绍


           集合是一种组合型的数据类型,分为可变的set和不可变的frozenset。

          1、可变集合set

           集合set是一种无序的、唯一的的元素集,与数学中集合的概念类似,可对其进行交、并、差、补等逻辑运算。不支持索引、切片等序列操作,但仍支持成员关系运算符in-not in、推导式等操作。在特定的场合中可以体现出非常优秀的执行效率。

           下面分别介绍了集合的创建以及对集合中元素进行增添、删除等修改操作。

    #通过以下这种方法创建集合
    set() -> new empty set object
    set(iterable) -> new set object    #iterable可以是String、Tuple、List、Dict、Set 
    1 #例子
    2 set('xyz')    #{'x', 'y', 'z'}
    3 set((1, 2, 3))   #{1, 2, 3}
    4 set([1, 2, 3])   #{1, 2, 3}
    5 set({'a':1, 'b':2, 'c':3})  #{'a', 'b', 'c'}
    6 set({1, 2, 3})   #{1, 2, 3}
    7 #错误示范
    8 set(1)
      TypeError: 'int' object is not iterable
     1 #集合中元素唯一性
     2 set([1, 1, 2, 2, 3, 3, 4, 3, 'a', 'b', 'c', 'a', 'b'])  #{1, 2, 3, 4, 'a', 'b', 'c'}
     3 #集合推导式
     4 set(x**2 for x in range(1, 6))    #{1, 4, 9, 16, 25}
     5 #由于set是一个可变集合,可进行以下操作
     6 s1 = set(range(5))   #{0, 1, 2, 3, 4}
     7 #增加一个元素
     8 s1.add(5)     #{0, 1, 2, 3, 4, 5}
     9 #删除一个集合中的元素,若集合中没有该元素则返回错误
    10 s1.remove(0)   #{1, 2, 3, 4, 5}
    11 #随机删除一个元素,并返回删除的元素
    12 s1.pop()   #1
    13 # 指定删除集合中的一个元素,若没有这个元素,则什么也不做
    14 s1.discard(1)    #{2, 3, 4, 5}
    15 s1.discard('a')   #{2, 3, 4, 5}
    16 #清空集合中所有元素
    17 s1.clear()    #set()

          2、不可变集合frozenset

          frozenset冻结集合,即不可变集合。frozenset的元素是固定的,一旦创建后就无法增加、删除和修改。其最大的优点是使用hash算法实现,所以执行速度快,而且frozenset可以作为dict字典的Key,也可以成为其他集合的元素。

    #Build an immutable unordered collection of unique elements.
    frozenset() -> empty frozenset object
    frozenset(iterable) -> frozenset object  
     1 #例子
     2 frozenset()   #frozenset()
     3 frozenset([1, 2, 3, 'abc'])   #frozenset({1, 2, 3, 'abc'})
     4 #frozenset集合作为dic的key和value
     5 f = frozenset([1,2,3])
     6 d = {f:'a'}   #{frozenset({1, 2, 3}): 'a'}
     7 d2 = {'a':f}  #{'a': frozenset({1, 2, 3})}
     8 #set集合不可以作为dic的key和value
     9 f2 = set([1, 2, 3])
    10 d3 = {f2:1}   #TypeError: unhashable type: 'set'

          3、set、frozenset共有的内建函数

           这里主要包括集合与字符串、列表、字典、集合之间的交集、并集、差集以及集合之间的关系,由于目前还未接触很多,http://python.jobbole.com/87597/对此进行了详细介绍,本文不再进行介绍。

  • 相关阅读:
    python10.31
    python10.29
    python10.28
    python10.27
    python10.25
    python10.24
    python10.23
    四边形不等式与决策单调
    0x57~0x59
    0x55~0x56
  • 原文地址:https://www.cnblogs.com/beyondChan/p/10927630.html
Copyright © 2020-2023  润新知