自學Python2.5-基本數據類型-set集合

Python set集合

1、 set集合概述python

①set集合,是一個無序且不重複的元素集合。
②集合對象是一組無序排列的可哈希的值,集合成員能夠作字典中的鍵。
③集合支持用in和not in操做符檢查成員,由len()內建函數獲得集合的基數(大小), 用 for 循環迭代集合的成員。可是由於集合自己是無序的,不能夠爲集合建立索引或執行切片(slice)操做,也沒有鍵(keys)可用來獲取集合中元素的值。
④集合set是Python中一種基本數據類型,它分爲可變集合(set)和不可變集合(frozenset)兩種。ide

2、set的操做函數

1. set的建立post

集合中set括號中須要的參數的數據類型有:序列(包括字符串、列表、元組),字典或者是另外一個集合,可是不能是數值類型,如int類型。ui

s1=()  #建立空集合set()
print(s1)
s2=set(['carlos','alex','eric','tony']) #列表作參數
print(s2)
s3=set('carlos')#字符串作參數
print(s3)
s4=set((1,2,3))#元組作參數
print(s4)
s5=set({'name':'carlos','age':'26'})#元組作參數 , 只取值字典中的key
print(s5)

輸出this

()
{'tony', 'carlos', 'alex', 'eric'}
{'l', 'o', 'a', 's', 'r', 'c'}
{1, 2, 3}
{'age', 'name'}spa

s=set(['carlos','alex','eric','tony','carlos']) #set中的元素是無序不重複 的,能夠利用這個特色去除列表中的重複元素
print(s)

輸出
{'alex', 'carlos', 'tony', 'eric'}rest

2. set集合的添加code

2.1 add(self, *args, **kwargs)把要傳入的元素做爲一個總體添加到集合中orm

s=set(['carlos','alex','eric','tony'])
print(s)
s.add('gary')
print(s)

輸出

{'tony', 'carlos', 'alex', 'eric'}
{'tony', 'alex', 'gary', 'eric', 'carlos'}

2.2 update(self, *args, **kwargs) 要傳入的元素拆分紅單個字符,存於集合中,並去掉重複的字符

s=set(['carlos','alex','eric','tony'])
print(s)
s.update('amy')
print(s)

輸出

{'tony', 'carlos', 'alex', 'eric'}
{'a', 'm', 'eric', 'tony', 'y', 'carlos', 'alex', 'gary'}

3.集合的刪除 
   集合的刪除操做使用的方法跟列表是同樣的,使用的也是remove方法,若不存在,報錯

s=set(['carlos','alex','eric','tony'])
print(s)
s.remove('alex')
print(s)

輸出

{'tony', 'eric', 'alex', 'carlos'}
{'tony', 'eric', 'carlos'}

4. 集合的遍歷

s=set(['carlos','alex','eric','tony'])
for i in s:
  print(i)

輸出

tony
eric
alex
carlos

s=set(['carlos','alex','eric','tony'])
for idx, i in enumerate(s) :
  print(idx,i)

輸出

0 tony
1 alex
2 eric
3 carlos

3、集合的一些操做符  

1.交集 python中求集合的交集使用的符號是「&」,返回連個集合的共同元素的集合,即集合的交集。 

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1&s2
print(s)

輸出

{'o', 's', 'r', 'c', 'l', 'a'}
{'x', 'l', 'a', 'e'}
{'l', 'a'}

2.並集(合集) Python中求集合的並集用的是符號「|」,返回的是兩個集合全部的並去掉重複的元素的集合。

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1|s2
print(s)

輸出

{'s', 'r', 'c', 'o', 'l', 'a'}
{'e', 'l', 'a', 'x'}
{'s', 'x', 'r', 'c', 'o', 'e', 'l', 'a'}

3.差集  Python中差集使用的符號是減號「-」  ,返回的結果是在集合st1中但不在集合s2中的元素的集合

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1-s2
print(s)

輸出

{'l', 's', 'r', 'a', 'c', 'o'}
{'a', 'l', 'x', 'e'}
{'r', 'c', 's', 'o'}

4.查看兩個集合的不一樣之處,使用的difference函數,等價於差集

   不一樣指的是集合s3相對於集合s1,不一樣的地方,也就是全部在集合s1中,而再也不集合s2中的的元素組成的新集合。

s1=set('carlos')
s2=set('alex')
s=s1-s2
s3=s1.difference(s2)
print(s)
print(s3)

輸出

{'r', 'o', 'c', 's'}
{'r', 'o', 'c', 's'}

5. 集合的範圍判斷

  集合可使用大於(>)、小於(<)、大於等於(>=)、小於等於(<=)、等於(==)、不等於(!=)來判斷某個集     合是否徹底包含於另外一個集合,也可使用子父集判斷函數。 返回值爲True 或者False。

6. 集合的成員運算符  使用成員運算符,in和not in,判斷某個對象是不是集合中的成員

s1=([1,2,3,4,5,])
result=1 in s1
print(result)
result=4 not in s1
print(result)

輸出

True
False

7. 求集合的長度  使用len()函數

s1=([1,2,3,4,5,])
result=len(s1)
print(result)

輸出 5

4、set的方法

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): # real signature unknown
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs): # real signature unknown
        """
        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): # real signature unknown
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): # real signature unknown
        """
        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): # real signature unknown
        """
        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): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass

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

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

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

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

    def remove(self, *args, **kwargs): # real signature unknown
        """
        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): # real signature unknown
        """
        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): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass

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

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

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

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

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

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

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

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

    def __iand__(self, *args, **kwargs): # real signature unknown
        """ 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): # real signature unknown
        """ Return self|=value. """
        pass

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

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

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

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

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

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

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

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

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

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

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

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

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

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

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

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

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

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

    __hash__ = None
set源碼

一、add(self, *args, **kwargs)    將元素 添加到集合s中,若重複則不進行任何操做

     update(self, *args, **kwargs) 將集合 x 併入原集合s中,x 還能夠是列表,元組,字典等,x 能夠有多個,用逗號分開

二、clear(self, *args, **kwargs)  刪除 set 中的全部元素

三、copy(self, *args, **kwargs)  複製集合

四、difference(self, *args, **kwargs)  返回一個新的 set 包含 s1中有可是s2中沒有的元素(生成新集合,不改變原集合)

     difference_update(self, *args, **kwargs) 返回一個新的 set 包含 s1和 s2中不重複的元素(改變原集合)

s1=set('carlosalexamy')
s2=set('alextong')
s3=s1.difference(s2)
s4=s1.difference_update(s3)
print(s3)
print(s4)

輸出

{'s', 'c', 'm', 'r', 'y'}
None

五、discard(self, *args, **kwargs)    若是在 set 「s」中存在元素 x, 則刪除。若不存在,不會引起錯誤

s1=set(['carlos','alex','eric','tony'])
s1.discard('tony')
print(s1)

輸出{'carlos', 'alex', 'eric'}

六、intersection(self, *args, **kwargs)  取交集,新建一個set

   intersection_update(self, *args, **kwargs) 取交集,修改原來set

7. isdisjoint(self, *args, **kwargs) 若是沒有交集,返回Ture

8. issubset(self, *args, **kwargs)  是不是子集

9. issuperset(self, *args, **kwargs) 是不是父集

10. pop(self, *args, **kwargs)  刪除而且返回 set 「s」中的一個不肯定的元素, 若是爲空則引起 KeyError (在原集合拿走一個隨機元素,並獲得這個元素, 這個是兩個動做)

s1=set(['carlos','alex','eric','tony'])
result=s1.pop()
print(s1)
print(result)

輸出

{'carlos', 'tony', 'alex'}
eric

11. remove(self, *args, **kwargs)   從 set 「s」中刪除元素 x, 若是不存在則引起 KeyError(在原集合拿走一個指定元素,無返回值)

s1=set(['carlos','alex','eric','tony'])
result=s1.remove('alex')
print(s1)
print(result)

輸出

{'carlos', 'tony', 'eric'}
None 

12.  symmetric_difference(self, *args, **kwargs) 取差集,新建一個set

       symmetric_difference_update(self, *args, **kwargs) 取差集,改變原來set

13.  union(self, *args, **kwargs)   取並集

 5、 舉例子

相關文章
相關標籤/搜索