Python 字典與集合


 本節導航:


一、Dictionary 字典

  字典(dict)是在列表后我們學到的第二種可變的容器模型,可以存儲任意類型的對象。字典,顧名思義就像是我們經常使用的新華字典或英語詞典一樣,具有極快的查找速度,可以幫助我們快速的查找到所需要的東西。在Python中,字典是以鍵值對(‘key’-'value')的形式表現的,每個鍵值對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({}中。

  在這里需要注意的是:dict是無序的;跟多變的 value 不同的是 key 具有唯一性;key 的數據類型必須是固定的不可變的,如:數字、字符串、元組等,而 value 就沒有那么多的要求可以為任意的Python數據類型。演示實例如下:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math
print(math_score)           #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
 demo_1 = {'Madonna': 89, 1: 'iennvv', 1.34: {'Madonna': 89}, ("ifne", "fjie"): [1, 2, 3]} print(demo_1)               #{'Madonna': 89, 1: 'iennvv', 1.34: {'Madonna': 89}, ('ifne', 'fjie'): [1, 2, 3]}
 demo_2 = {'Madonna': 89, {'iem': "ofem"}:99}        #TypeError: unhashable type: 'dict'
demp_3 = {[1, 2, 3]: 45}                            #TypeError: unhashable type: 'list'

  這時候我們已經知道如何創建一個正確的字典了,雖然這個創建的這個字典的長度有點慘不容睹,但是它已經屬於一個正常的字典了,可以實現索引字典該有的功能,接下來就讓我們從“增”“刪”“查”“改”四個方面進一步的接觸它吧。

“增”:Python中我們可以通過三種方法實現字典的添加功能:第一種是通過字典名加中括號的方式直接添加,需要用 = 連接 value 值(也可以實現通過 key  value 的修改);第二種是通過 setdefault() ,如果輸入的 key 存在於字典中,無論輸入的 value 正確與否(也可不輸),返回 key 的值,如果 key 不存在於字典之中時,將會把括號內的 key value 自動添加成為字典中一對新的鍵值對(如果沒有 value 的話默認值為 none );第三種方法是在有兩個字典的前提下存在的,通過內置 update() 實現將兩個字典的合並(如果在兩個字典中有相交的鍵值對就進行覆蓋,如果沒有就添加到原字典中)。具體演示實例如下:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math
 math_score['Baade'] = 77                       #新增一個鍵值對 'Baade': 77
print(math_score)                              #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77}

print(math_score.setdefault('Madonna'))        #89
print(math_score.setdefault('Madonna', 22))    #89
math_score.setdefault('Aine')                  #'Aine' 不存在字典當中,新建鍵值對,由於沒有設置value,默認為none
print(math_score)                       #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None}
math_score.setdefault('Mary', 100)             #'Mary' 不存在字典當中,新建鍵值對
print(math_score)                    #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None, 'Mary': 100}
 g = {1:2, 3:4, 'Madonna': 89}                  #新建一個字典 g
math_score.update(g)                           #將新字典 g 並入原字典 math_score 中
print(math_score)                  #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None, 'Mary': 100, 1: 2, 3: 4}
    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass
setdefault() update() 部分源代碼

“刪”:與列表相同的是字典當中也提供了多種的“刪”方法,只不過具體的內容有所不同。pop()  刪除指定的鍵並返回相應的值,如果字典中沒有該鍵則顯示 KeyError 錯誤;popitem() 打印刪除的鍵值對(以元組的形式返回),隨機返回並刪除字典中的一對鍵和值(一般刪除末尾對);clear() 清空字典;del 可以刪除字典中的內容或是直接刪除字典(參照列表)。具體演示實例如下:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math

print(math_score.pop('Cory'))     #99 打印刪除指定鍵的值
print(math_score)                 #{'Madonna': 89, 'Annie': 65, 'Nelly': 89}

print(math_score.popitem())       #('Nelly', 89)     打印刪除的鍵值對(以元組的形式返回)隨機返回並刪除字典中的一對鍵和值(一般刪除末尾對)
print(math_score)                 #{'Madonna': 89, 'Annie': 65, 'Nelly': 89}
 math_score.clear() #清空字典
print(math_score)                 #{}
 math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} del math_score['Madonna']         #刪除字典中的 'Madonna'
print(math_score)                 #{'Cory': 99, 'Annie': 65, 'Nelly': 89}

del math_score                    #直接刪除字典 math_score
print(math_score)                 #NameError: name 'math_score' is not defined
    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass
pop() popitem() clear() 部分源代碼

“查”:典中我們可以通過 key 查詢所對應的 value 值,這也是它最主要的功能之一,這時候有兩種方法以供選擇:第一種是直接通過字典名加中括號的方式查詢,如果 key 值存在則返回其 value 值,如果不存在則報 KeyError 錯誤;另外一種是直接使用內置的 get() ,在括號內輸入 key ,如果 key 存在返回 value 值,否之返回 none 。還有另外兩種需求,當我們想要獲得字典中所有的 key 時需要用到內置的 key() ,打印字典中的所有 key ,也可以通過 value() 獲取字典中所有的 value 值。具體演示實例如下:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math

print(math_score['Madonna'])        #89
print(math_score['amd'])           #KeyError: 'amd'

print(math_score.get('Madonna'))    #89
print(math_score.get('Madon'))      #None

print(math_score.keys())            #dict_keys(['Madonna', 'Cory', 'Annie', 'Nelly'])

print(math_score.values())          #dict_values([89, 99, 65, 89])
    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass
get() keys() values() 部分源代碼

注:還可以用 in 直接判斷,key 是否在字典中,但是它只會返回True or False 。

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math

print('Madonna' in math_score)        #True

“改”:字典中的只能通過字典名加中括號的方式進行修改,如果 key 輸入出錯,則會新建一對鍵值對。

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math
 math_score['Madonna'] = 100         #修改字典中 'Madonna' 對應的 value 值
print(math_score)                   #{'Madonna': 100, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
 math_score['Madna'] = 88            #'Madna' 不在字典中,在字典中創建一個一個新的鍵值對 'Madna':88
print(math_score)                   #{'Madonna': 100, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Madna': 88}

其他:item() 把一個字典轉換為列表 ;copy()  淺copy 和在列表中的功能相似,在這里就不做具體陳述了;fromkeys() 返回一個新的命令,它具有可迭代的鍵值和與值相等的值,簡單的來講就是創建了一個新的字典,逗號前面的為新字典的 key ,后面為每個新字典賦予的 value 值。具體實例如下:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math
 d = math_score.items()        #轉換為列表
print(d)                      #dict_items([('Madonna', 89), ('Cory', 99), ('Annie', 65), ('Nelly', 89)])
 b = math_score.copy()         #淺copy
print(b)                      #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
 c = math_score.fromkeys([1, 2, 3], 'text')        #生產一個新的字典
print(c)                      #{1: 'text', 2: 'text', 3: 'text'}
e = math_score.fromkeys([1, 2, 3], ['111', 'ss', 'sss']) print(e)                      #{1: ['111', 'ss', 'sss'], 2: ['111', 'ss', 'sss'], 3: ['111', 'ss', 'sss']}
    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass

    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass
item() copy() fromkeys() 部分源代碼

注:在 fromkeys() 中有一個小坑,當前面列表中的 key 值有重復的時候它會默認刪除多余的( key 具有唯一性),不會報錯。當然這個怎么會屬於一個坑呢,這只是 Python 中內部優化的一個體現,在這里我所說的坑是,當使用 fromkeys() 生產一個新的字典時,它的 value 值也屬於一種淺 copy ”,修改一個鍵值對中的 value 值,其他的 value 值也會隨着一起發生變化。

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math
 a = math_score.fromkeys([1, 2, 3], ['math', {'name':'Nelly'}, 120])     #使用 fromkeys() 在原有的字典中聲明一個新的字典 
print(a)                #{1: ['math', {'name': 'Nelly'}, 120], 2: ['math', {'name': 'Nelly'}, 120], 3: ['math', {'name': 'Nelly'}, 120]}
 a[1][0] = 'English'     #修改新字典鍵為 1 的 value 值
print(a)                #{1: ['English', {'name': 'Nelly'}, 120], 2: ['English', {'name': 'Nelly'}, 120], 3: ['English', {'name': 'Nelly'}, 120]}

  我們在列表中知道可以通過切片或是通過 for 循環的方式進行列表的循環打印,那么在字典中我們該如何來做呢?在這里我就不賣關子了,我們可以通過兩種簡單的 for 來進行循環打印。與列表不同的是,在打印的時候我們要加上 value 值,不然它只會打印 key 。我就不進行語言的陳述了,直接利用例子來進行展示:

math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}         #創建一個班級數學成績字典 math #第一種方法
for i in math_score:                #循環打印出字典的 key
    print(i)                        #Madonna Cory Annie Nelly

for i in math_score:                #循環打印出字典的 鍵值對
    print(i, math_score[i])         #Madonna 89 Cory 99 Annie 65 Nelly 89

#第二種方法
for k, v in math_score.items():     #循環打印出字典的 鍵值對
    print(k, v)                     #Madonna 89 Cory 99 Annie 65 Nelly 89

區別:上面一個比下面一個高效很多,因為上面直接通過索引把value值取出來,而下面一個在運算的過程中有把字典轉換為列表的過程,明顯會造成它的效率降低。

  在最好我們來學習下字典中最為重要的一個點,那就是字典是可以層層嵌套的(層數無限,相信你也不會閑着無聊建那么多層)。

class_exam_score = {                                #就簡單的創建了一個三層的字典,具體的內容有點重復,就湊合看吧
    'class_one': {
        'math': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'English': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'Chinese': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
    },
    'class_two': {
        'math': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'English': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'Chinese': {
            'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
    },
    'class_three': {
        'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89},
        'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
    }
}
print(class_exam_score)         #{'class_one': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}, 'class_two': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}, 'class_three': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}}

print(class_exam_score['class_three']['English']['Madonna'])        #打印三班英語考試中'Madonna'的成績
簡單三級字典

二、Sets 集合

   寫到這里終於快結束了,容我先歇口氣!在前面我們一口氣學完了列表、元組、字典,是不是感覺自己快炸了,方括號、括號、大括號什么的兩臉懵逼,不慫不怕,讓暴風雨來的更猛烈些吧!!!接下來進入集合的學習吧:

  首先需要了解下如何去建立一個新的集合:第一種方法是我們可以通過大括號 {} 內加內容用逗號( , ) 隔開的方式直接創建一個集合;第二種可以使用 set() 方法將已有的列表(或元組)構建成一個無序的集合。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
print(type(list_1))                         #<class 'list'>
 set_1 = set(list_1)                         #把列表 list_1 轉換為集合 set_1
print(type(set_1))                          #<class 'set'>
print(set_1)                                #{1, 2, 3, 4, 5, 6, 66, 22}
print(set((1, 2, 3, 4, 4)))                 #{1, 2, 3, 4}    由元組創建集合
 set_2 = {1, 3, 3, 4, 4, 77}                 #直接創建一個集合 set_2
print(type(set_2))                          #<class 'set'>
print(set_2)                                #{1, 3, 4, 5, 77}

  啊!特么我的值怎么被吃了?怎么變短了那么多??系統還我的值啊!!!別激動,別激動,冷靜下。

  冷靜下來后仔細觀察我們就會發現,被“吃”的值是列表(或元組)中重復的東西,這時候我們似乎發現了集合中一個不可告人的大秘密,它好像具有“去重”的功能,是不是很熟悉?對,你猜對了。這點集合跟字典類似,具有“天生去重”(自動把集合內部重復的部分刪除)的功能,我們可以理解集合是一個無序的、不重復的數據組合,但是集合與字典也存在明顯的不同,我們可以形象的把集合看成只有 key ,不具備存儲 value 的功能。

    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
set() 部分源代碼

注:集合和字典一樣是無序的(無法通過數字進行索引),而且內部的數據類型必須是固定的不可變的。

  除了“天生去重”,集合還可以測試兩組數據之間的交集、並集、差集、子集等,與我們初中所學習的集合知識有很大的相同部分,接下來讓我一一道來。

交集:交集,顧名思義就是取兩個(或多個)集合相交(相同)的部分,然后生成一個新集合。我在這里提供兩種求交集的方法:第一我們可以使用內置的 intersection() 方法求取兩個集合的交集;還可以直接通過位運算符 & (且)連接兩個集合,求取交集。騷年,老夫看你骨骼奇異,再免費送你一種可以判斷兩個集合是否有交集的辦法 isdisjoint() ,不過它有個不好的地方是,它是在兩個集合有一個空的交集的時候返回 True ,即當有交集的時候返回 False ,這點可不要弄混了哦。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2

print(set_1.intersection(set_2))            #{1, 3, 4} 將兩個集合的交集作為一個新集合返回。(即兩個集合中的相同的部分)
print(set_1 & set_2)                        #{1, 3, 4}
print(set_1.isdisjoint(set_2))              #False 兩個集合有相同的部分。
    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
intersection() isdisjoint() 部分源代碼

差集:將兩個或多個集合的差值作為一個新集合返回,我們可以通過 difference() 方法 可以實現這一功能;和交集相同,也可以使用運算符 - 來實現。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2)                      #set_2: {1, 3, 4, 77}

print(set_1.difference(set_2))              #{66, 5, 6}
print(set_2.difference(set_1))              #{77}
print(set_1 - set_2)                        #{66, 5, 6}
print(set_2 - set_1)                        #{77}
    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
difference() 部分源代碼

注:與交集不同的是,差集中的兩個集合前后有順序關系,可以理解為到底是誰減誰,前后順序不同會導致結果的差異。

並集:與交集相同,並集中沒有前后集合的位置關系,即無論哪個在前哪個在后結果相同。Python中也提供了兩種方法來求集合的並集,union() 返回不同集合的所有元素形成一個新集合;也可以使用位運算符 | (並)來實現。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2)                      #set_2: {1, 3, 4, 77}

print(set_1.union(set_2))                   #{1, 66, 3, 4, 5, 6, 77}
print(set_2.union(set_1))                   #{1, 66, 3, 4, 5, 6, 77}
print(set_1 | set_2)                        #{1, 66, 3, 4, 5, 6, 77}
    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
union() 部分源代碼

子集:可以通過 issubset() 方法確定另外一個集合是否包含此集合(括號內的元素是否包含前一個元素內),如果包含返回 True 。形象記憶:在前面一個是“兒子”后面一個是“爸爸”的情況下返回 True 。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2)                      #set_2: {1, 3, 4, 77}
set_3 = {1, 3} print(set_1.issubset(set_2))                #False
print(set_3.issubset(set_1))                #True
print(set_1.issubset(set_3))                #False
    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set. """
        pass
issubset() 部分源代碼

父集:通過 issuperset() 來確定這個集合是否包含另外一個集合,即當前面一個是“爸爸”后面一個是“兒子”的情況下返回 True 。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2)                      #set_2: {1, 3, 4, 77}
set_3 = {1, 3} print(set_1.issuperset(set_2))              #False 
print(set_1.issuperset(set_3))              #True
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. """
        pass
issuperset() 部分源代碼

對稱差集:將兩個集合的對稱差作為一個新集合返回。是不是感覺很懵逼,別怕,還有我在,說白了對稱差集就是把兩個集合中不同的部分拿出來形成一個新的集合。可以使用 symmetric_difference() 或運算符 ^ 來實現對稱差集,集合放置沒有前后順序。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) set_2 = {1, 3, 3, 4, 4, 77}                 #直接定義一個集合 set_2
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2)                      #set_2: {1, 3, 4, 77}

print(set_1.symmetric_difference(set_2))            #{66, 5, 6, 77}
print(set_1 ^ set_2)                                #{66, 5, 6, 77}
    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
symmetric_difference() 部分源代碼

“增”:add() 向集合中添加單個元素,如果如果元素已經存在,則沒有效果;update() 向集合中添加多個元素,效果和add() 類似。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1) print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
 set_1.add(7777)                             #添加元素 7777
print(set_1)                                #{1, 66, 3, 4, 5, 6, 7777}
set_1.add(66)                               #添加元素 66
print(set_1)                                #{1, 66, 3, 4, 5, 6, 7777}
set_1.update([1, 222, 3333])                # 添加多項
print(set_1)                                #{1, 66, 3, 4, 5, 6, 7777, 3333, 222}
    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 update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        pass
add() update() 部分源代碼

“刪”:集合中我們可以選擇好多種不同的刪除的方法,remove() 刪除括號內的指定元素,如果該元素不在集合內,則報錯;pop()  隨意刪除一個集合內的元素,並返回其刪除的值;discard() 刪除括號內的指定元素,如果該元素是集合的一個成員,從集合中移除這個元素,否則什么都不做,返回None;剩下的就是clear() 和 del 了,用法和前面相同就不具體描述了。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1)                         #將列表轉換為集合
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
 set_1.remove(1)                         #指定刪除一個元素,如果不出在會報錯
print(set_1)                             #{66, 3, 4, 5, 6}
print(set_1.pop())                         #66 #隨意刪除一個並返回刪除的值,括號內不需要輸入內容
print(set_1)                      #{3, 4, 5, 6}
print(set_1.discard(1))           #None #刪除指定值,如果指定值在不在它都不會報錯,打印的話只會返回none
print(set_1)                      #{3, 4, 5, 6}
print(set_1.discard(3))           #None
print(set_1)                      #{3, 4, 5, 6}
set_1.clear()                     #清空集合
print(set_1)                      #set()
del set_1                         #刪除集合
print(set_1)                      #NameError: name 'set_1' is not defined
    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 pop(self, *args, **kwargs): # real signature unknown
        """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """
        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 clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass
remove() pop() discard() clear() 部分源代碼

“查”:在集合中我們只能通過in 或是 not  in 來判斷,一個元素是否在集合中。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1)                         #將列表轉換為集合
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}

print(1 in set_1)                           #True
print(3 not in set_1)                       #False

集合的比較:通過運算符 < > == 比較兩個集合的關系,返回True 或False。與判斷子、父集類似,可以用來判斷子集和父集。

set_1 = {1, 3, 5, 777} set_2 = {1, 3} print(set_1 < set_2)            # False 
print(set_1 == set_2)           # False 
print(set_1 > set_2)            # True

“其他”:len() 獲取集合的長度(集合內元素的個數);copy() 淺copy。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1)                         #將列表轉換為集合
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}

print(len(set_1))                           #6
set_2 = set_1.copy()                        #淺copy
print(set_2)                                #{1, 66, 3, 4, 5, 6}

未知的三個東東:哎,這三個真是不怎么在干嘛,無論怎么的蹂躪他們,要么返回 None,要么報錯,關鍵就是它不跟我們玩,實在不知道用在什么地方,歡迎一起探討。

list_1 = [1, 3, 4, 5, 6, 66, 3, 6]          #創建一個列表 list_1
set_1 = set(list_1)                         #將列表轉換為集合
print('set_1:', set_1)                      #set_1: {1, 66, 3, 4, 5, 6}
set_2 = {1, 3, 3, 4, 4, 77} print(set_1.intersection_update(set_2))             #None
print(set_1.difference_update(set_2))               #None
print(set_1.symmetric_difference_update(set_1))     #None
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass

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

    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass
intersection_update() difference_update() symmetric_difference_update() 部分源代碼

延伸:當面海量列表數據時,怎樣做才能刪除列表中重復的元素呢?這里就提供一種解決的方法,具體演示代碼如下:

a = [1, 2, 3, 43, 31, 2]            #新建一個列表
b = set(a)                           #將列表轉為集合
print(b)                             #{1, 2, 3, 43, 31}
 c = [i for i in b]                   #循環集合
print(c)                             #[1, 2, 3, 43, 31]


免責聲明!

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



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