1. 程式人生 > >第二章 python中重要的數據結構(下)

第二章 python中重要的數據結構(下)

alt 檢查 testin and 淺復制 .py remove arr cti

二、元組(tuple):不可變序列 

跟list一樣,也是一種序列,唯一不同的是,元組元素不能被修改,通常用(, ,)表示元組,也可以不加括號。

技術分享
 1 #創建元組
 2 >>> 1,2,3
 3 (1, 2, 3)
 4 >>> t = (1,2,3)
 5 >>> t
 6 (1, 2, 3)
 7 #創建空元組
 8 >>> t1 = () 
 9 >>> t1
10 ()
11 #創建只有一個元素的元組,這裏註意必須帶上逗號
12 >>> t2 = (1,)
13 >>> t2
14 (1,)
15 #也可以用tuple()函數創建元組
16 >>> b = tuple(‘abc‘)
17 >>> b
18 (‘a‘, ‘b‘, ‘c‘)
技術分享

【訪問】:跟list一樣,支持索引和分片訪問。

【區別】:元組和列表的區別及適用的地方?

  1、元組可以充當字典中的鍵,列表則不可

  2、元組不像list那樣有內建函數。

三、集合(set) 

【定義】:集合是一組無序的不重復的值

技術分享
 1 >>> basket = {‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘}
 2 >>> print(basket)                      # show that duplicates have been removed
 3 {‘orange‘, ‘banana‘, ‘pear‘, ‘apple‘}
 4 >>> ‘orange‘ in basket                 # fast membership testing
 5 True
 6 >>> ‘crabgrass‘ in basket
 7 False
 8 
 9 >>> # Demonstrate set operations on unique letters from two words
10 ...
11 >>> a = set(‘abracadabra‘)
12 >>> b = set(‘alacazam‘)
13 >>> a                                  # unique letters in a
14 {‘a‘, ‘r‘, ‘b‘, ‘c‘, ‘d‘}
15 >>> a - b                              # letters in a but not in b
16 {‘r‘, ‘d‘, ‘b‘}
17 >>> a | b                              # letters in either a or b
18 {‘a‘, ‘c‘, ‘r‘, ‘d‘, ‘b‘, ‘m‘, ‘z‘, ‘l‘}
19 >>> a & b                              # letters in both a and b
20 {‘a‘, ‘c‘}
21 >>> a ^ b                              # letters in a or b but not both
22 {‘r‘, ‘d‘, ‘b‘, ‘m‘, ‘z‘, ‘l‘}
技術分享

四、字典(Dictionaries) 

【定義】字典是一組鍵值對,其中key可以是數字、字符串、元組。

【創建】用大括號表示,key-value結構,鍵值之間用冒號隔開,不同的鍵值對之間通過逗號分隔,如下:

1 >>> dict = {‘Tome‘:‘1341‘,‘Helen‘:‘2030‘}
2 >>> dict
3 {‘Tome‘: ‘1341‘, ‘Helen‘: ‘2030‘}
4 >>> dict1 = {}
5 >>> dict1
6 {}

【基本操作】

  len(dict)返回字典鍵值對數量

  dict[k]返回key為k的值

  dict[k]改變key為k的值

  del dict[k]刪除鍵為k的項

  k in dict檢查dict中是否含有鍵為k的項

技術分享
  1 #!/usr/python
  2 
  3 people = {
  4     ‘Alice‘:{
  5         ‘phone‘:‘2341‘,
  6         ‘addr‘:‘Foo drive 23‘
  7     },
  8 
  9     ‘Beth‘:{
 10         ‘phone‘:‘2003‘,
 11         ‘addr‘:‘Bar street 32‘
 12     },
 13 
 14     ‘Cecil‘:{
 15         ‘phone‘:‘3212‘,
 16         ‘addr‘:‘Baz avenue 90‘
 17     }
 18 
 19 }
 20 
 21 labels = {
 22     ‘phone‘:‘phone number‘,
 23     ‘addr‘:‘address‘
 24 }
 25 
 26 name = raw_input(‘Name: ‘)
 27 request = raw_input(‘Phone number(p) or address(a)? ‘)
 28 if request == ‘p‘:
 29     key = ‘phone‘
 30 if request == ‘a‘:
 31     key = ‘addr‘
 32 
 33 if name in people:
 34     print "%s‘s %s is %s." % (name,labels[key],people[name][key])
技術分享

運行結果:

1 [[email protected] python]# python dict.py 
2 Name: Alice
3 Phone number(p) or address(a)? p
4 Alice‘s phone number is 2341.

【方法】

1、clear()方法:清空字典所有項,原地操作。

技術分享
 1 >>> x = {}
 2 >>> y = x #並不是簡單的賦值,這裏可以理解為x,y共同指向一個字典
 3 >>> x[‘key‘]=‘value‘
 4 >>> x
 5 {‘key‘: ‘value‘}
 6 >>> y
 7 {‘key‘: ‘value‘}
 8 >>> x = {}
 9 >>> x
10 {}
11 >>> y
12 {‘key‘: ‘value‘}
技術分享 技術分享
 1 >>> x = {}
 2 >>> y = x
 3 >>> x[‘key‘] = ‘value‘
 4 >>> x
 5 {‘key‘: ‘value‘}
 6 >>> y
 7 {‘key‘: ‘value‘}
 8 >>> x.clear() #註意clear方法清除原地
 9 >>> x
10 {}
11 >>> y
12 {}
技術分享

2、copy()方法:返回一個相同值得新字典,淺復制

1 >>> a = {‘username‘:‘admin‘,‘machines‘:[‘foo‘,‘bar‘]}
2 >>> b = a.copy()
3 >>> b[‘username‘]=‘lsls‘
4 >>> b[‘machines‘].remove(‘bar‘)
5 >>> a          #替換不能改變值,但是修改可以改變原字典值
6 {‘username‘: ‘admin‘, ‘machines‘: [‘foo‘]} 

可以通過深復制,讓原字典保持不變:

技術分享
1 >>> from copy import deepcopy
2 >>> d = {}
3 >>> d[‘name‘] = [‘aa‘,‘bb‘]
4 >>> c = d.copy()
5 >>> dc = deepcopy(d)
6 >>> dc[‘name‘].append(‘cc‘)
7 >>> d
8 {‘name‘: [‘aa‘, ‘bb‘]}
技術分享

3、get(key)方法:通過key訪問字典值,如果字典不存在key,不會報錯,返回none

4、keys()和iterkeys()方法:keys方法將字典中的鍵以列表形式返回,而iterkeys則返回針對鍵的叠代器

5、pop(key)方法:刪除指定key的鍵值項

6、popitem()方法:隨機刪除一個鍵值項

7、values()和itervalues()方法:values方法將字典中的鍵以列表形式返回,而itervalues則返回針對鍵的叠代器

8、update(item)方法:利用一個字典項更新另一個字典

1 >>> d = {‘title‘:‘python study‘,‘url‘:‘www.python.com‘}
2 >>> x = {‘title‘:‘.net study‘} 
3 >>> d.update(x)
4 >>> d
5 {‘url‘: ‘www.python.com‘, ‘title‘: ‘.net study‘}

至此,python中常用的數據結構就學習的差不多了。

   

第二章 python中重要的數據結構(下)