python字典和集合

來源:互聯網
上載者:User

1. 字典字典是python中唯一的映射類型,採用索引值對(key-value)的形式儲存資料。python對key進行雜湊函數運算,根據計算的結果決定value的儲存地址,所以字典是無序儲存的,且key必須是可雜湊的。可雜湊表示key必須是不可變類型,如:數字、字串、只含不可變類型元素的元組(1,2,3,’abc’)、實現__hash__()方法的自訂對象(因為__hash__()須返回一個整數,否則會出現異常:TypeError: an integer is required)。可以用hash(obj)檢測對象是否是可雜湊的。  >>> class HashEnable(object):  ...    def  __hash__(self):  ...         return 1 >>> he = HashEnable()  >>> hash(he)  1 >>> d = {he:1}  >>> d = {['1',2]:2}  Traceback (most recent call last):    File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'   1.1 字典常用操作 (1)建立字典  >>> d1 = {}  >>> d2 = {'player':'QVOD','game':'kw'}  >>> d1,d2 ({}, {'player': 'QVOD', 'game': 'kw'})    >>> d3 = dict((['name','alex'],['sex','man']))  >>> d3  {'name': 'alex', 'sex': 'man'}  >>> d33 = d3.copy()  >>> d33  {'name': 'alex', 'sex': 'man'}    >>> d4 = {}.fromkeys(('alex','zhou'),1)  >>> d4  {'alex': 1, 'zhou': 1}  >>> d5 = {}.fromkeys(('alex','zhou'))  >>> d5  {'alex': None, 'zhou': None}   (2)遍曆字典 ps:訪問一個不存在的key時,會發生KeyError異常,訪問前可使用in或not in判斷一下。  >>> d = {'name':'alexzhou','sex':'man'}    >>> for key in d:  ...     print '%s,%s' %(key,d[key])  ...   name,alexzhou  sex,man    >>> d['name']  'alexzhou' >>> d2 = {'name':'alexzhou','age':100}  >>> print 'name: %s,age: %d' %(d2['name'],d2['age'])  name: alexzhou,age: 100   >>> d2['sex']  Traceback (most recent call last):       File "<stdin>", line 1, in <module> KeyError: 'sex'   >>> 'sex' in d2  False >>> 'name' in d2  True   (3)更新字典  >>> d = {'name':'alexzhou','age':100}  >>> d['age'] = 88 >>> d  {'age': 88, 'name': 'alexzhou'}  >>> d.pop('age')  88 >>> d {'name': 'alexzhou'}  >>> d.clear()  >>> d  {}   1.2 常用內建函數 (1)cmp() 字典的比較:首先是字典的大小,然後是鍵,最後是值  >>> d1 = {'abc':1,'efg':2}  >>> d2 = {'abc':1,'efg':2,'h':3}  >>> cmp(d1,d2)  -1 >>> d3 = {'ab':1,'efg':2}  >>> cmp(d1,d3)  1 >>> d4 = {'abc':1,'efg':3}  >>> cmp(d1,d4)  -1 >>> d5 = {'abc':1,'efg':2}  >>> cmp(d1,d5)  0   (2)len() 返回索引值對的數目  >>> d = {'abc':1,'efg':2} >>> len(d)  2   (3)keys()、values() 、items() keys()返回一個包含字典所有鍵的列表 values()返回一個包含字典所有值的列表 items()返回一個包含索引值元組的列表  >>> d = {'name':'alex','sex':'man'}  >>> d.keys()  ['name', 'sex']  >>> d.values()  ['alex', 'man']  >>> d.items()  [('name', 'alex'), ('sex', 'man')]   (4)dict.get(key,default=None) 返回字典中key對應的value,若key不存在則返回default  >>> d = {'name':'alex','sex':'man'}  >>> d.get('name','not exists')  'alex' >>> d.get('alex','not exists')  'not exists'   (5)dict.setdefault(key,default=None) 若key存在,則覆蓋之前的值,若key不存在,則給字典添加key-value對  >>> d.setdefault('name','zhou')  'alex' >>> d  {'name': 'alex', 'sex': 'man'}  >>> d.setdefault('haha','xixi')  'xixi' >>> d  {'haha': 'xixi', 'name': 'alex', 'sex': 'man'}   (6)dict.update(dict2) 將字典dict2的索引值對添加到dict  >>> d = {'name':'alex','sex':'man'}  >>> d1 = {'age':100,'address':'shenzhen'}  >>> d.update(d1)  >>> d  {'age': 100, 'address': 'shenzhen', 'name': 'alex', 'sex': 'man'   (7)sorted(dict) 返回一個有序的包含字典所有key的列表  >>> sorted(d)  ['address', 'age', 'name', 'sex']   2. 集合set python中集合對象(set)是一組無序排列的可雜湊的值,包含兩種類型:可變集合(set)和不可變集合(frozenset),所以set不是可雜湊的,frozenset是可雜湊的,能當作字典的鍵。  >>> s = set('a')  >>> hash(s) Traceback (most recent call last): File "<stdin>", line 1, in <module>  TypeError: unhashable type: 'set'   >>> fs = frozenset('a')  >>> hash(fs)  -1305064881317614714   2.1 集合常用操作(1)建立集合  >>> s = set('alexzhou')  >>> s  set(['a', 'e', 'h', 'l', 'o', 'u', 'x', 'z'])  >>> fs = frozenset('alexzhou')  >>> fs  frozenset(['a', 'e', 'h', 'l', 'o', 'u', 'x', 'z'])   (2)遍曆集合  >>> for e in s:  ...     print e  ...   a  e  h  l  o  u  x  z   (3)更新集合(add/update/remove/discard/pop/clear(-=)) s.add(obj):添加對象obj s.update(s1): 用s1中的成員修改s,s現在包含s1的成員 s.remove(obj):從集合s中刪除obj,若obj不存在,則引發KeyError錯誤 s.discard(obj): 如果obj是s的成員,則刪除obj s.pop(): 刪除集合s中任意一個對象,並返回 s.clear(): 刪除集合s中所有元素  >>> s = set('alexzhou')  >>> s.update('hai')  >>> s  set(['a', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z'])  >>> s.add('hai')  >>> s  set(['a', 'hai', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z'])  >>> s.remove('hai')  >>> s  set(['a', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z'])  >>> s -= set('alex')  >>> s  set(['i', 'h', 'o', 'u', 'z'])  >>> s.pop()  'i' >>> s  set(['h', 'z', 'u', 'o'])  >>> s.discard('h')  >>> s  set(['z', 'u', 'o'])  >>> s.clear()  >>> s  set([])  >>> fs = frozenset('alexzhou')  >>> fs.add('z')  Traceback (most recent call last):    File "<stdin>", line 1, in <module>  AttributeError: 'frozenset' object has no attribute 'add'   (4) 集合比較 s1.issubset(s2):檢測s1是否是s2的子集,是則返回True,否則返回False s1.issuperset(s2):檢測s1是否是s2的超集,是則返回True,否則返回False  >>> s = set('alexzhou')  >>> fs = frozenset('alexzhou')  >>> s == fs  True >>> s2 = set('alexzhou')  >>> s == s2  True>>> s3 = set('alexzhouj')  >>> s > s3  False >>> s < s3  True >>> s   (5)聯合union操作(s1|s2,s1.union(s2)) 產生的集合的每個元素至少是其中一個集合的成員。如果左右兩邊的集合類型相同,則產生的結果是相同的,若不同,則產生的結果跟左運算元相同。  >>> s1 = set('abc')  >>> fs = frozenset('de')   >>> s1 | fs  set(['a', 'c', 'b', 'e', 'd'])    >>> type(s1 | fs)  <type 'set'>  >>> type(fs | s1)  <type 'frozenset'>    >>> s2 = set('fg')  >>> type(s1 | s2)  <type 'set'>  >>> s1.union(fs)  set(['a', 'c', 'b', 'e', 'd'])  >>> type(s1.union(fs))  <TYPE ?set?>  >>> type(fs.union(s1))  <TYPE ?frozenset?>   (6)交集s1&s2,補集s1-s2,異或s1^s2 交集:新集合中的元素同時是s1和s2的元素 –> s1.intersection(s2) 補集:新集合中的元素只屬於s1,不屬於 –> s1.difference(s2) 異或:新集合中的元素不能同時屬於s1和s2 –> s1.symmetric_difference(s2)  >>> fs = frozenset('de')  >>> s = set('def')  >>> s & fs  set(['e', 'd'])  >>> s - fs  set(['f'])  >>> fs - s  frozenset([])  >>> s ^ fs  set(['f'])  >>> s.intersection(fs)  set(['e', 'd'])  >>> s.difference(fs)  set(['f'])  >>> s.symmetric_difference(fs)  set(['f'])  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.