Python基本資料型別之set

morra發表於2016-10-13

一、定義

set是一個無序且不重複的元素集合。

集合物件是一組無序排列的可雜湊的值,集合成員可以做字典中的鍵。集合支援用in和not in操作符檢查成員,由len()內建函式得到集合的基數(大小), 用 for 迴圈迭代集合的成員。但是因為集合本身是無序的,不可以為集合建立索引或執行切片(slice)操作,也沒有鍵(keys)可用來獲取集合中元素的值。

set和dict一樣,只是沒有value,相當於dict的key集合,由於dict的key是不重複的,且key是不可變物件因此set也有如下特性:

  1. 不重複

  2. 元素為不可變物件

二、建立


s = set()
s = {11,22,33,44}  #注意在建立空集合的時候只能使用s=set(),因為s={}建立的是空字典

a=set('boy')
b=set(['y', 'b', 'o','o'])
c=set({"k1":'v1','k2':'v2'})
d={'k1','k2','k2'}
e={('k1', 'k2','k2')}
print(a,type(a))
print(b,type(b))
print(c,type(c))
print(d,type(d))
print(e,type(e))

OUTPUT:
{'o', 'b', 'y'} <class 'set'>
{'o', 'b', 'y'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{'k1', 'k2'} <class 'set'>
{('k1', 'k2', 'k2')} <class 'set'>

三、基本操作

比較


se = {11, 22, 33}
be = {22, 55}
temp1 = se.difference(be)        #找到se中存在,be中不存在的集合,返回新值
print(temp1)        #{33, 11}
print(se)        #{33, 11, 22}

temp2 = se.difference_update(be) #找到se中存在,be中不存在的集合,覆蓋掉se
print(temp2)        #None
print(se)           #{33, 11},

刪除

discard()、remove()、pop()


se = {11, 22, 33}
se.discard(11)
se.discard(44)  # 移除不存的元素不會報錯
print(se)

se = {11, 22, 33}
se.remove(11)
se.remove(44)  # 移除不存的元素會報錯
print(se)

se = {11, 22, 33}  # 移除末尾元素並把移除的元素賦給新值
temp = se.pop()
print(temp)  # 33
print(se) # {11, 22}

取交集


se = {11, 22, 33}
be = {22, 55}

temp1 = se.intersection(be)             #取交集,賦給新值
print(temp1)  # 22
print(se)  # {11, 22, 33}

temp2 = se.intersection_update(be)      #取交集並更新自己
print(temp2)  # None
print(se)  # 22

判斷


se = {11, 22, 33}
be = {22}

print(se.isdisjoint(be))        #False,判斷是否不存在交集(有交集False,無交集True)
print(se.issubset(be))          #False,判斷se是否是be的子集合
print(se.issuperset(be))        #True,判斷se是否是be的父集合

合併


se = {11, 22, 33}
be = {22}

temp1 = se.symmetric_difference(be)  # 合併不同項,並賦新值
print(temp1)    #{33, 11}
print(se)       #{33, 11, 22}

temp2 = se.symmetric_difference_update(be)  # 合併不同項,並更新自己
print(temp2)    #None
print(se)             #{33, 11}

取並集


se = {11, 22, 33}
be = {22,44,55}

temp=se.union(be)   #取並集,並賦新值
print(se)       #{33, 11, 22}
print(temp)     #{33, 22, 55, 11, 44}

更新


se = {11, 22, 33}
be = {22,44,55}

se.update(be)  # 把se和be合併,得出的值覆蓋se
print(se)
se.update([66, 77])  # 可增加迭代項
print(se)

集合的轉換


se = set(range(4))
li = list(se)
tu = tuple(se)
st = str(se)
print(li,type(li))
print(tu,type(tu))
print(st,type(st))

OUTPUT:
[0, 1, 2, 3] <class 'list'>
(0, 1, 2, 3) <class 'tuple'>
{0, 1, 2, 3} <class 'str'>

四、原始碼


class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): 
        """新增"""
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass

    def clear(self, *args, **kwargs): 
        """清除"""
        """ Remove all elements from this set. """
        pass

    def copy(self, *args, **kwargs): 
        """淺拷貝"""
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs): 
        """比較"""
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)
        """
        pass

    def difference_update(self, *args, **kwargs): 
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): 
        """刪除"""
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.
        """
        pass

    def intersection(self, *args, **kwargs): 
        """
        Return the intersection of two sets as a new set.
        
        (i.e. all elements that are in both sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): 
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): 
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): 
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs): 
        """ Report whether this set contains another set. """
        pass

    def pop(self, *args, **kwargs): 
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

    def remove(self, *args, **kwargs): 
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.
        """
        pass

    def symmetric_difference(self, *args, **kwargs): 
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

    def symmetric_difference_update(self, *args, **kwargs): 
        """ Update a set with the symmetric difference of itself and another. """
        pass

    def union(self, *args, **kwargs): 
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)
        """
        pass

    def update(self, *args, **kwargs): 
        """ Update a set with the union of itself and others. """
        pass

    def __and__(self, *args, **kwargs): 
        """ Return self&value. """
        pass

    def __contains__(self, y): 
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, *args, **kwargs): 
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): 
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs): 
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): 
        """ Return self>value. """
        pass

    def __iand__(self, *args, **kwargs): 
        """ Return self&=value. """
        pass

    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        
        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs): 
        """ Return self|=value. """
        pass

    def __isub__(self, *args, **kwargs): 
        """ Return self-=value. """
        pass

    def __iter__(self, *args, **kwargs): 
        """ Implement iter(self). """
        pass

    def __ixor__(self, *args, **kwargs): 
        """ Return self^=value. """
        pass

    def __len__(self, *args, **kwargs): 
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): 
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): 
        """ Return self<value. """
        pass

    @staticmethod 
    def __new__(*args, **kwargs): 
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): 
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): 
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs): 
        """ Return value&self. """
        pass

    def __reduce__(self, *args, **kwargs): 
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs): 
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs): 
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs): 
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs): 
        """ Return value^self. """
        pass

    def __sizeof__(self): 
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, *args, **kwargs): 
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs): 
        """ Return self^value. """
        pass

    __hash__ = None

相關文章