12.5、python基礎(chǔ)數(shù)據(jù)類(lèi)型(set集合)

基礎(chǔ)數(shù)據(jù)類(lèi)型(set集合)

認(rèn)識(shí)集合

  由一個(gè)或多個(gè)確定的元素所構(gòu)成的整體叫做集合。

  集合中的元素有三個(gè)特征:

    1.確定性(集合中的元素必須是確定的)

    2.互異性(集合中的元素互不相同。例如:集合A={1,a},則a不能等于1)

    3.無(wú)序性(集合中的元素沒(méi)有先后之分),如集合{3,4,5}和{3,5,4}算作同一個(gè)集合。

  *集合概念存在的目的是將不同的值存放到一起,不同的集合間用來(lái)做關(guān)系運(yùn)算,無(wú)需糾結(jié)于集合中某個(gè)值

集合的定義

  s = {1,2,3,1}

#定義可變集合>>> set_test=set('hello')

>>> set_test

{'l', 'o', 'e', 'h'}#改為不可變集合frozenset>>> f_set_test=frozenset(set_test)

>>> f_set_test

frozenset({'l', 'e', 'h', 'o'})

集合的常用操作及關(guān)系運(yùn)算

  元素的增加

  單個(gè)元素的增加 : add(),add的作用類(lèi)似列表中的append

  對(duì)序列的增加 : update(),而update類(lèi)似extend方法,update方法可以支持同時(shí)傳入多個(gè)參數(shù):

>>> a={1,2}

>>> a.update([3,4],[1,2,7])

>>> a

{1, 2, 3, 4, 7}

>>> a.update("hello")

>>> a

{1, 2, 3, 4, 7, 'h', 'e', 'l', 'o'}

>>> a.add("hello")

>>> a

{1, 2, 3, 4, 'hello', 7, 'h', 'e', 'l', 'o'}

  元素的刪除

  集合刪除單個(gè)元素有兩種方法:

    元素不在原集合中時(shí):

      set.discard(x)不會(huì)拋出異常

      set.remove(x)會(huì)拋出KeyError錯(cuò)誤

>>> a={1,2,3,4}

>>> a.discard(1)

>>> a

{2, 3, 4}

>>> a.discard(1)

>>> a

{2, 3, 4}

>>> a.remove(1)

Traceback (most recent call last):

? File "<input>", line 1, in <module>

KeyError: 1

  pop():由于集合是無(wú)序的,pop返回的結(jié)果不能確定,且當(dāng)集合為空時(shí)調(diào)用pop會(huì)拋出KeyError錯(cuò)誤,

  clear():清空集合

>>> a={3,"a",2.1,1}

>>> a.pop()

1

>>> a.pop()

3

>>> a.clear()

>>> a

set()

>>> a.pop()

Traceback (most recent call last):

? File "<input>", line 1, in <module>

KeyError: 'pop from an empty set'

  集合操作


    |,|=:合集

a = {1,2,3}

b = {2,3,4,5}print(a.union(b))print(a|b)

    &.&=:交集

a = {1,2,3}

b = {2,3,4,5}print(a.intersection(b))print(a&b)

    -,-=:差集

a = {1,2,3}

b = {2,3,4,5}print(a.difference(b))print(a-b)?

    ^,^=:對(duì)稱(chēng)差集

a = {1,2,3}

b = {2,3,4,5}print(a.symmetric_difference(b))print(a^b)


  包含關(guān)系

    in,not in:判斷某元素是否在集合內(nèi)

   ?。剑?!=:判斷兩個(gè)集合是否相等

    兩個(gè)集合之間一般有三種關(guān)系,相交、包含、不相交。在Python中分別用下面的方法判斷:

set.isdisjoint(s):判斷兩個(gè)集合是不是不相交

set.issuperset(s):判斷集合是不是包含其他集合,等同于a>=b

set.issubset(s):判斷集合是不是被其他集合包含,等同于a<=b

集合的工廠(chǎng)函數(shù)

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? ? ? ? """

? ? ? ? 相當(dāng)于s1-s2


? ? ? ? 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功能相同,刪除元素不存在時(shí)不會(huì)拋出異常


? ? ? ? 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? ? ? ? """

? ? ? ? 相當(dāng)于s1&s2


? ? ? ? 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? ? ? ? """

? ? ? ? 相當(dāng)于s1<=s2


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

? ? ? ? 相當(dāng)于s1>=s2


? ? ? ? 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? ? ? ? """

? ? ? ? 相當(dāng)于s1^s2


? ? ? ? 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? ? ? ? """

? ? ? ? 相當(dāng)于s1|s2


? ? ? ? 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容