Python的集合類型詳解17

一,集合

    1.集合一組無序排列的可哈希的值;

    2.支持集合關係測試,例如:in、not in、迭代等;

        例如:

In [35]: s1=set(1,2,3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-35-6a12ec048247> in <module>()
----> 1 s1=set(1,2,3)

TypeError: set expected at most 1 arguments, got 3

In [36]: s1=set([1,2,3])

In [37]: s1
Out[37]: {1, 2, 3}

In [38]: type(s1)
Out[38]: set

    3.不支持索引、元素獲取和切片;

    4.集合的類型:set()、frozenset()

    5.集合沒有特定語法格式,只能通過工廠函數創建;

        工廠函數:http://www.programgo.com/article/5639846274/

二,集合類型的方法和操作


項目描述
len(s)返回s中項目數
s.copy()製作s的一份副本
s.difference(t)求差集。返回所有在s中,但不在t中的項目
s.intersection(t)求交集。返回所有同時在s和t中的項目
s.isdisjoint(t)如果s和t沒有相同項,則返回True
s.issubset(t)如果s是t的一個子集,則返回True
s.issuperset(t)如果s是t的一個超級,則返回True
s.symmetric_difference(t)求對稱差集。返回所有在s或t中,但又不同時在這兩個集合中的項
s.union(t)求並集。返回所有在s或t中的項

操作描述操作描述
s | ts和t的並集len(s)集合中項數
s & ts和t的交集max(s)最大值
s - t求差集min(s)最小值
s ^ t求對稱差集

    例如:

In [40]: set.                            //set方法
set.add                          set.intersection                 set.pop
set.clear                        set.intersection_update          set.remove
set.copy                         set.isdisjoint                   set.symmetric_difference
set.difference                   set.issubset                     set.symmetric_difference_update
set.difference_update            set.issuperset                   set.union
set.discard                      set.mro                          set.update

In [41]: s2 = set([2,3,4])      //並集

In [42]: s1 & s2
Out[42]: {2, 3}

In [43]: s1.symmetric_difference
s1.symmetric_difference         s1.symmetric_difference_update  

In [43]: s1.symmetric_difference(s2)         //對稱差集
Out[43]: {1, 4}

In [44]: s3 = set('xyz')     //迭代

In [45]: s3
Out[45]: {'x', 'y', 'z'}

In [46]: s3.pop()             //刪除或彈出元素 
Out[46]: 'y'

In [47]: s3.pop()
Out[47]: 'x'

In [48]: s3.pop()
Out[48]: 'z'

In [49]: s3.pop()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-49-aa97d01de6b1> in <module>()
----> 1 s3.pop()

KeyError: 'pop from an empty set'

In [56]: s3 = set('xyz')             //支持異構

In [57]: id(s1)
Out[57]: 19454768

In [59]: print s1,s3
set([1, 2, 3]) set(['y', 'x', 'z'])

In [60]: s1.update(s3)

In [61]: id(s1)
Out[61]: 19454768

In [62]: id(s3)
Out[62]: 21995832

In [63]: print s1
set([1, 2, 3, 'y', 'x', 'z'])

In [64]: print s3
set(['y', 'x', 'z'])

In [65]: s1.add(7)      //添加元素

In [66]: print s1
set([1, 2, 3, 7, 'y', 'x', 'z'])

In [67]: s1.add('Jerry')

In [68]: print s1
set([1, 2, 3, 7, 'y', 'x', 'z', 'Jerry'])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章