集合操作


一、集合基礎

1、創建集合

  • 使用set類創建集合

  在使用set類創建集合是=時,需要為set類的構造方法提供一個列表或者元組類型的值,用於建立集合的數據源;這也就是說set類可以將元組或列表轉為集合,並且去除重復元素,元素順序可能也會被打亂,因為集合是無序的。

#利用列表創建集合
s=set([1,2,3]) print(s) #{1, 2, 3}

 #利用元組創建集合

 s=set((1,2,3))
 print(s) #{1, 2, 3}

 
  • 使用{}直接創建
s={1,2,3}
print(type(s))#<class 'set'>

2、集合特性

(1)無序性

集合中的值是平等的,元素之間是無序的,無法通過索引和分片進行操作。

(2)互異性

集合中任意兩個元素之間是不同的,即每個元素只能出現一次,常常用於去重應用。

(3)確定性

集合內的元素是不可變數據類型,例如,集合、列表、字典都不能作為集合的元素,因為它們都是可變的。

3、元素檢測

判斷一個元素是否屬於該集合,使用in,如果在就返回True,如果不在就返回False。

s=set("hello")
print("h" in s)#True

4、集合遍歷

######遍歷字符串#####
s=set("hello") for i in s: print(i) #########輸出##### o e l h


#######遍歷元組####

 s={(1,2),(3,4),(5,6)}
  for item in s:
    print(item)
#########輸出##########
  (5, 6)
  (3, 4)
  (1, 2)

二、集合方法

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  向集合中添加一個元素
  • clear 從集合中移除所有元素
  • copy 返回集合的淺拷貝
  • difference 將兩個或多個集合的差集作為一個新集合返回
  • difference_update 從這個集合中刪除另一個集合的所有元素
  • discard 移除一個已經存在於集合中的元素(如果元素不存在,則不執行任何操作)
  • intersection 將兩個集合的交集作為一個新集合返回
  • intersection_update 自身集合和另一個的交集來更新這個集合
  • isdisjoint 如果兩個集合有一個空交集,返回 True
  • issubset 如果另一個集合包含這個集合,返回 True
  • issuperset 如果這個集合包含另一個集合,返回 True
  • pop 刪除並返回任意的集合元素(如果集合為空,會拋出 KeyError異常)
  • remove 刪除集合中的一個元素(如果元素不存在,會拋出KeyError異常)
  • symmetric_difference 將兩個集合的對稱差作為一個新集合返回(兩個集合合並刪除相同部分,其余保留)
  • symmetric_difference_update 用自己和另一個的對稱差來更新這個集合
  • union 將集合的並集作為一個新集合返回
  • update 用自己和另一個的並集來更新這個集合 

1、add()

s={1,2,4,}
s.add(5)
print(s)#{1, 2, 4, 5}

2、clear()

s={'hell0','world'}
s.clear()
print(s)#set()

3、copy ()

s1={1,2,3,}
s2=s1.copy()
print(s2)#{1, 2, 3}

4、difference()

s1={'a','b','c'}
s2={'a','d','c','e'}
#求出s1和s2之間的差集,保留s1中不同的元素
print(s1.difference(s2))#{'b'}
print(s1-s2)#{'b'}

#保留s2中相同的元素
print(s2.difference(s1))#{'d', 'e'}
print(s2-s1)#{'d', 'e'}

5、difference_update()

s1={1,2,4,5,}
s2={2,4,6,8}
s3={6}
s1.difference_update(s2)
#從s1中刪除存在s2的元素
print(s1)#{1, 5}

#從s2中刪除存在s3的元素
s2.difference_update(s3)
print(s2)#{8, 2, 4}

6、discard()

s={"a","b","c"}
s.discard("b")
#從s中移除元素b
print(s)#{'a', 'c'}

7、intersection()

s1={1,2,4,5,}
s2={2,4,6,8}
#將s1和s2求交集並且返回新的集合
print(s1.intersection(s2))#{2, 4}
print(s1&s2)#{2, 4}

8、intersection_update()

s1={'a','b','c'}
s2={'a','d','c','e'}
#相當於s1-s2,這與差集difference差不多
s1.intersection_update(s2)
print(s1)#{'a', 'c'}

9、isdisjoint()

s1={'a','b','c'}
s2={'a','d','c','e'}
#判斷s1與s2之間是否有空交集,如果沒有返回False
print(s1.isdisjoint(s2))#False

10、issubset()

s1={1,2,3}
s2={2}
#因為s1集合包含s2,所以返回True
print(s2.issubset(s1))#True

11、issuperset()

s1={1,2,3}
s2={2}
#因為s1集合包含s2,所以返回True
print(s1.issuperset(s2))#True

它與issubset的區別在於,包含的集合作為方法的調用者,被包含集合作為方法的參數。

12、pop()

s={1,3,5,2,8,3,9}
#隨機刪除元素並且返回刪除元素
print(s.pop())#1
print(s)#{2, 3, 5, 8, 9}

13、remove()

s={1,3,5,2,8,3,9}
#刪除指定元素並且無返回元素
print(s.remove(5))#None
print(s)#{1, 2, 3, 8, 9}

14、symmetric_difference()

s1={'a','b','c'}
s2={'a','d','c','e'}
#s1與s2中刪除相同元素,保留不同元素,求對稱差,相當於s1-s2與s2-s1的並集
print(s1.symmetric_difference(s2))#{'d', 'b', 'e'}

15、symmetric_difference_update()

s1={1,2,3,4,5}
s2={2,3,4}
s3={1,}
#將s1與s2集合的對稱集求出來,然后與s1集合進行更新
s1.symmetric_difference_update(s2)
print(s1)#{1, 5}
#將s3與s2集合的對稱集求出來,然后與s3集合進行更新
s3.symmetric_difference_update(s2)
print(s3)#{1, 2, 3, 4}

16、union()

s1={1,2,3,4,5}
s2={2,3,4}
#求出s1與s2的並集
print(s1.union(s2))#{1, 2, 3, 4, 5}
print(s1|s2)#{1, 2, 3, 4, 5}

17、update()

s1={1,2,3,4,5}
s2={2,3,4}
#對s1進行更新,相當於求兩個集合的並集
s1.update(s2)
print(s1)#{1, 2, 3, 4, 5}

三、集合常用方法

1、並集

使用union方法或者操作符“|”進行兩個或者多個集合求並集

namelist1={'alia','sanb','lige'}
namelist2={'alia','bobu'}
print(namelist1|namelist2)#{'alia', 'sanb', 'bobu', 'lige'}
print(namelist1.union(namelist2))#{'alia', 'sanb', 'bobu', 'lige'}

2、交集

使用intersection方法或者操作符“&”進行兩個或多個集合求交集

namelist1={'alia','sanb','lige'}
namelist2={'alia','bobu'}
print(namelist1&namelist2)#{'alia'}
print(namelist1.intersection(namelist2))#{'alia'}

3、差集

使用difference方法或者操作符“-”進行兩個或多個集合求差集

namelist1={'alia','sanb','lige'}
namelist2={'alia','bobu'}
print(namelist1-namelist2)#{'sanb', 'lige'}
print(namelist1.difference(namelist2))#{'sanb', 'lige'}

4、對稱差集

使用symmetric_difference方法或者操作符“^”進行兩個或多個集合求對稱差集

namelist1={'alia','sanb','lige'}
namelist2={'alia','bobu'}
print(namelist1^namelist2)#{'sanb', 'bobu', 'lige'}
print(namelist1.symmetric_difference(namelist2))#{'sanb', 'bobu', 'lige'}

5、子集

使用issubset方法或者操作符“<”判斷當前集合是否是某個集合的子集

str1=set("hello")
str2=set("he")
#判斷str2是否是str1的子集
print(str2<str1)#True
print(str2.issubset(str1))#True

四、集合與函數

 1、len()

獲取集合中元素的個數

s={1,2,4,5,3,8}
print(len(s))#6

2、max()

獲取集合中最大的元素

s={1,2,4,5,3,8}
print(max(s))#8

3、min()

獲取集合中最小的元素

s={1,2,4,5,3,8}
print(min(s))#1

4、sum()

返回集合的所有元素之和

s={1,2,4,5,3,8}
print(sum(s))#23

5、sorted()

返回排序后的集合列表

s={1,2,4,5,3,8}
print(sorted(s))#[1, 2, 3, 4, 5, 8]

6、enumerate()

返回一個可迭代的enumerate的數據類型,迭代后可以取出索引值及其具體的值。

s={1,2,4,5,3,8}
print(enumerate(s))#<enumerate object at 0x00000000054DA558>
for i,j in enumerate(s):
    print(i,j)

#######輸出#######
    <enumerate object at 0x00000000054DA558>
    0 1
    1 2
    2 3
    3 4
    4 5
    5 8

7、all()

如果集合中的所有元素都是 True(或者集合為空),則返回 True。

s={0,1,2}
print(all(s))#False

#集合為空
s={}
print(all(s))#True

8、any()

如果集合中的所有元素都是 True,則返回 True;如果集合為空,則返回 False。

s={0,1,2}
print(any(s))#True

#集合為空
s={}
print(any(s))#False

五、frozenset只讀集合

class frozenset(object):
    """
    frozenset() -> empty frozenset object
    frozenset(iterable) -> frozenset object
    
    Build an immutable unordered collection of unique elements.
    """
    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 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 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 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 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 __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 __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, seq=()): # known special case of frozenset.__init__
        """ Initialize self.  See help(type(self)) for accurate signature. """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        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
frozenset類

  由於集合是可變的,所以不能作為集合的元素或者字典的key,但是可以利用frozenset類型將集合轉為可讀的,這樣就可以作為集合的元素以及字典的key。

#定義兩個集合s1,s2
s1=set("abcdefg")
s2=set([1,2,3,4])
#向s1,s2中添加元素
s1.add("h")
s2.add(5)
print(s1)
print(s2)
#############輸出##########
    {'a', 'd', 'c', 'f', 'e', 'h', 'g', 'b'}
    {1, 2, 3, 4, 5}

上面是正常的添加過程,但是s1集合添加s2,就會拋出異常

#定義兩個集合s1,s2
s1=set("abcdefg")
s2=set([1,2,3,4])
s1.add(s2)
print(s1)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-120-33029c9f337b> in <module>
      2 s1=set("abcdefg")
      3 s2=set([1,2,3,4])
----> 4 s1.add(s2)
      5 print(s1)

TypeError: unhashable type: 'set'

這時使用frozenset函數將s2集合轉為可讀集合,再進行添加

#定義兩個集合s1,s2
s1=set("abcdefg")
s2=set([1,2,3,4])

s1.add(frozenset(s2))
print(s1)

###########輸出######
{'a', 'd', 'c', frozenset({1, 2, 3, 4}), 'f', 'e', 'g', 'b'}

同理這時frozenset后的集合也可以作為字典的key。

dict={"name":"bright"}
s2=set([1,2,3,4])

dict.setdefault(frozenset(s2),[7,8,9])
print(dict)
##########輸出#########
{frozenset({1, 2, 3, 4}): [7, 8, 9], 'name': 'bright'}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM