python学习笔记(五)集合(set)
set 擁有類似 dict 的特點:可以用{}花括號來定義;其中的元素沒有序列,也就是是非序列類型的數(shù)據(jù);而且,set 中的元素不可重復,這就類似 dict 的鍵.
set 也有一點 list 的特點:有一種集合可以原處修改.
下面通過實驗,進一步理解創(chuàng)建 set 的方法:
>>> s1 = set("qiwsir") >>> s1 set(['q', 'i', 's', 'r', 'w'])把 str 中的字符拆解開,形成 set.特別注意觀察:qiwsir 中有兩個 i,但是在 s1 中,只有一個 i,也就是集合中元素不能重復。
>>> s2 = set([123,"google","face","book","facebook","book"]) >>> s2 set(['facebook', 123, 'google', 'book', 'face'])在創(chuàng)建集合的時候,如果發(fā)現(xiàn)了重復的元素,就會過濾一下,剩下不重復的。而且,從 s2 的創(chuàng)建可以看出,查看結果是顯示的元素順序排列與開始建立是不同,完全是隨意顯示的,這說明集合中的元素沒有序列。
>>> s3 = {"facebook",123} #通過{}直接創(chuàng)建 >>> s3 set([123, 'facebook'])然后用 help()可以找到每個函數(shù)的具體使用方法,下面列幾個例子:
add, update
>>> help(set.add)Help on method_descriptor:add(...) Add an element to a set. This has no effect if the element is already present.下面在交互模式這個最好的實驗室里面做實驗:
>>> a_set = {} #我想當然地認為這樣也可以建立一個 set >>> a_set.add("qiwsir") #報錯.看看錯誤信息,居然告訴我 dict 沒有 add.我分明建立的是 set 呀. Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'add' >>> type(a_set) #type 之后發(fā)現(xiàn),計算機認為我建立的是一個 dict <type 'dict'>特別說明一下,{}這個東西,在 dict 和 set 中都用.但是,如上面的方法建立的是 dict,不是 set.這是 Python 規(guī)定的.要建立 set,只能用前面介紹的方法了.
>>> a_set = {'a','i'} #這回就是 set 了吧 >>> type(a_set)<type 'set'> #果然>>> a_set.add("qiwsir") #增加一個元素 >>> a_set #原處修改,即原來的 a_set 引用對象已經(jīng)改變 set(['i', 'a', 'qiwsir'])>>> b_set = set("python") >>> type(b_set) <type 'set'> >>> b_set set(['h', 'o', 'n', 'p', 't', 'y']) >>> b_set.add("qiwsir") >>> b_set set(['h', 'o', 'n', 'p', 't', 'qiwsir', 'y'])>>> b_set.add([1,2,3]) #報錯.list 是不可哈希的,集合中的元素應該是 hashable 類型。 Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'>>> b_set.add('[1,2,3]') #可以這樣! >>> b_set set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'qiwsir', 'y'])除了上面的增加元素方法之外,還能夠從另外一個 set 中合并過來元素,方法是 set.update(s2)
>>> help(set.update) update(...)Update a set with the union of itself and others.>>> s1 set(['a', 'b']) >>> s2 set(['github', 'qiwsir']) >>> s1.update(s2) #把 s2 的元素并入到 s1 中. >>> s1 #s1 的引用對象修改 set(['a', 'qiwsir', 'b', 'github']) >>> s2 #s2 的未變 set(['github', 'qiwsir'])pop, remove, discard, clear
>>> help(set.pop) pop(...)Remove and return an arbitrary set element.Raises KeyError if the set is empty.>>> b_set set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'qiwsir', 'y']) >>> b_set.pop() #從 set 中任意選一個刪除,并返回該值 '[1,2,3]' >>> b_set.pop() 'h' >>> b_set.pop() 'o' >>> b_set set(['n', 'p', 't', 'qiwsir', 'y'])>>> b_set.pop("n") #如果要指定刪除某個元素,報錯了. Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: pop() takes no arguments (1 given)set.pop()是從 set 中任意選一個元素,刪除并將這個值返回.但是,不能指定刪除某個元素.報錯信息中就告訴我們了,pop()不能有參數(shù).此外,如果 set 是空的了,也報錯.這條是幫助信息告訴我們的,看官可以試試.
要刪除指定的元素,怎么辦?
>>> help(set.remove)remove(...)Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.set.remove(obj)中的 obj,必須是 set 中的元素,否則就報錯.試一試:
>>> a_set set(['i', 'a', 'qiwsir']) >>> a_set.remove("i") >>> a_set set(['a', 'qiwsir']) >>> a_set.remove("w") Traceback (most recent call last):File "<stdin>", line 1, in <module> KeyError: 'w'跟 remove(obj)類似的還有一個 discard(obj):
>>> help(set.discard)discard(...)Remove an element from a set if it is a member.If the element is not a member, do nothing.與 help(set.remove)的信息對比,看看有什么不同.discard(obj)中的 obj 如果是 set 中的元素,就刪除,如果不是,就什么也不做,do nothing.新聞就要對比著看才有意思呢.這里也一樣.
>>> a_set.discard('a') >>> a_set set(['qiwsir']) >>> a_set.discard('b') >>>在刪除上還有一個絕殺,就是 set.clear(),它的功能是:Remove all elements from this set.(看官自己在交互模式下 help(set.clear))
>>> a_set set(['qiwsir']) >>> a_set.clear() >>> a_set set([]) >>> bool(a_set) #空了,bool 一下返回 False. False集合運算
喚醒一下中學數(shù)學(準確說是高中數(shù)學中的一點知識)中關于集合的一點知識,當然,你如果是某個理工科的專業(yè)大學畢業(yè),更應該熟悉集合之間的關系。
元素與集合的關系
就一種關系,要么術語某個集合,要么不屬于。
>>> aset set(['h', 'o', 'n', 'p', 't', 'y']) >>> "a" in aset False >>> "h" in aset True集合與集合的關系
假設兩個集合 A、B
- A 是否等于 B,即兩個集合的元素完全一樣
在交互模式下實驗
>>> a set(['q', 'i', 's', 'r', 'w']) >>> b set(['a', 'q', 'i', 'l', 'o']) >>> a == b False >>> a != b True- A 是否是 B 的子集,或者反過來,B 是否是 A 的超集。即 A 的元素也都是 B 的元素,但是 B 的元素比 A 的元素數(shù)量多。
判斷集合 A 是否是集合 B 的子集,可以使用 A<B,返回 true 則是子集,否則不是。另外,還可以使用函數(shù) A.issubset(B)判斷。
>>> a set(['q', 'i', 's', 'r', 'w']) >>> c set(['q', 'i']) >>> c<a #c 是 a 的子集 True >>> c.issubset(a) #或者用這種方法,判斷 c 是否是 a 的子集 True >>> a.issuperset(c) #判斷 a 是否是 c 的超集 True>>> b set(['a', 'q', 'i', 'l', 'o']) >>> a<b #a 不是 b 的子集 False >>> a.issubset(b) #或者這樣做 False- A、B 的并集,即 A、B 所有元素,如下圖所示
可以使用的符號是“|”,是一個半角狀態(tài)寫的豎線,輸入方法是在英文狀態(tài)下,按下"shift"加上右方括號右邊的那個鍵。找找吧。表達式是 A | B.也可使用函數(shù) A.union(B),得到的結果就是兩個集合并集,注意,這個結果是新生成的一個對象,不是將結合 A 擴充。
>>> a set(['q', 'i', 's', 'r', 'w']) >>> b set(['a', 'q', 'i', 'l', 'o']) >>> a | b #可以有兩種方式,結果一樣 set(['a', 'i', 'l', 'o', 'q', 's', 'r', 'w']) >>> a.union(b) set(['a', 'i', 'l', 'o', 'q', 's', 'r', 'w'])- A、B 的交集,即 A、B 所公有的元素,如下圖所示
我在實驗的時候,順手敲了下面的代碼,出現(xiàn)的結果如下,看官能解釋一下嗎?(思考題)
>>> a and b set(['a', 'q', 'i', 'l', 'o'])- A 相對 B 的差(補),即 A 相對 B 不同的部分元素,如下圖所示
-A、B 的對稱差集,如下圖所示
>>> a set(['q', 'i', 's', 'r', 'w']) >>> b set(['a', 'q', 'i', 'l', 'o']) >>> a.symmetric_difference(b) set(['a', 'l', 'o', 's', 'r', 'w'])以上是集合的基本運算。在編程中,如果用到,可以用前面說的方法查找。不用死記硬背。
總結
以上是生活随笔為你收集整理的python学习笔记(五)集合(set)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python学习笔记(四)字典(dict
- 下一篇: 如何在多版本anaconda pytho