Python 學習筆記(十)Python集合(一),python學習筆記

來源:互聯網
上載者:User

Python 學習筆記(十)Python集合(一),python學習筆記

回顧

int/float/str/list/tuple/dict

整數型和浮點型是不可變的,不是序列

字串是不可變的,是序列

列表是可變的,是序列

元組是不可變的,是序列

字典是可變得,但不是序列

 

集合的基本概念

集合是基本的數學概念,它是集合論的研究對象,指具有某種特定性質的事物的總體,(在最原始的集合論─樸素集合論─中的定義,集合就是“一堆東西”。)集合裡的事物(“東西”),叫作元素。若然 x 是集合 A 的元素,記作 x ∈ A。

 

建立集合的方法

方法1:使用花括弧{} ;用花括弧所包裹的對象,就是一個集合

方法2:set()函數 一般使用這個函數建立集合

集合的元素沒有順序,不可重複

集合是不可雜湊的

 1 >>> {1,"python"} #使用花括弧建立集合 2 set(['python', 1]) 3 >>> type({1,"python"}) 4 <type 'set'> 5 >>> set("python") 6 set(['h', 'o', 'n', 'p', 't', 'y']) 7 >>> s= set("python") #使用set()建立集合 8 >>> s 9 set(['h', 'o', 'n', 'p', 't', 'y'])10 >>> s2=set(["baidu","google","ali"])11 >>> type(s2)12 <type 'set'>13 >>> s214 set(['baidu', 'google', 'ali']) #集合的元素沒有順序15 >>> s3=set([2,2,2,2,2]) 16 >>> s3  #集合元素不可重複17 set([2])18 >>>

可雜湊與不可雜湊

就是在其生存期內,不可變的對象,是可雜湊的,反之,可變的就是不可雜湊的

Python中所有不可變的都是可雜湊的,如數字、字串、元組

另列表、字典都是可變的,都是不可雜湊的

在字典中的Key鍵必須是可雜湊的,即不可變的對象

在集合中,集合的元素必須是可雜湊的,也就是說集合的元素必須是不可變對象

所以說用列表作為集合的元素,就報錯,因為列表是不可雜湊的對象

 1 >>> lst =[[1,2,3],"python"]   #用列表作為參數,建立一個集合,報錯list 是不可hash的 2 >>> s =set(lst) 3 Traceback (most recent call last): 4   File "<stdin>", line 1, in <module> 5 TypeError: unhashable type: 'list' 6 >>> d={[1,2,3]:"python"}   #建立一個字典,key為列表,報錯list 是不可hash的 7 Traceback (most recent call last): 8   File "<stdin>", line 1, in <module> 9 TypeError: unhashable type: 'list'   #list 是不可雜湊的10 >>>

集合與列表之間的轉換

 set() list() 

 1 >>> lst=[1,2,3] 2 >>> s =set(lst)  #將列錶轉換成集合 3 >>> s 4 set([1, 2, 3]) 5 >>> lst2 =list(s) #將集合轉換為列表 6 >>> lst2 7 [1, 2, 3] 8 >>> a =[1,2,2,3,3,6,6,8,9,0,0] #去除列表中的重複項,可使用set()集合 9 >>> s =set(a)10 >>> s11 set([0, 1, 2, 3, 6, 8, 9])12 >>> a =list(s) #去除重複後,再轉換為列表list13 >>> a14 [0, 1, 2, 3, 6, 8, 9]15 >>> s16 set([0, 1, 2, 3, 6, 8, 9]) 17 >>> hash(s) #返回hash值,也可判斷是否可雜湊,報錯不可雜湊,否則返回hash值18 Traceback (most recent call last):19   File "<stdin>", line 1, in <module>20 TypeError: unhashable type: 'set'21 >>> hash(1)22 1

建立不可變集合

frozenset() 建立不可變集合,是可雜湊的

1 >>> a2 [0,1,2,3,6,8,9]3 >>> s2 =frozenset(a)4 >>> type(s2)5 <type 'frozenset'>6 >>> hash(s2)7 20963408638 >>>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.