Python 快速入門(二)

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- Python 快速入門(二) (http://www.webasp.net/article/8/7721.htm)
-- 作者:未知
-- 發佈日期: 2003-09-13
原作者:xina

string vs list
string 也和 list 同為 sequence data type,也可作 slice operator,但 string 為 immutable object,不可修改其內容。


1 a = 'hello world!!'
2 print a[-7:], a[:5]

結果顯示 : world!! hello





1 a = 'hello'
2 print a[1]

結果顯示 : e



string 也和 list 一樣,可以 subscript (index) 其中的 item。python 並不像 C/C++ 般, python 並沒有獨立的 character type,string 的 subscripted item 為一長度為 1 的 string。

nested list
list 裡的 item 可以為另一個 list object,成一個巢狀的結構。


1 a = [ 1, 2, 3, ][ 'abc', 'cde', 3, 2], 5]
2 print a[3][1]

結果顯示 : cde





1 a = [1, 2, 3]
2 print len(a)

結果顯示 : 3



len() 函數傳回 sequence type object 的 size。

tuple & multiple assignment



1 a = 'foo'
2 a, b, c = 9, 8, a
3 print a, b, c

結果顯示 9 8 foo



行 2 稱為 multiple assignment,可以同時指定多個變數的內容。


1 a = 1, 2, 3, 4, 5
2 b = 1, 2, a[:3]
3 print a, b

結果顯示 : (1, 2, 3, 4, 5) (1, 2, (1, 2, 3))



行 1 bind name a 為 (1, 2, 3, 4, 5),python 定義為 tuple,同 string 為 immutable sequence data type, 不能改變 tuple object 的內容。a = 1, 2, 3, 4, 5 和 a = (1, 2, 3, 4, 5) 是相同的,稱之為 tuple packing, 把 1, 2, 3, 4, 5 這幾個 object 包成一個 tuple object。


1 a, b, c = 1, 2, 3
2 (e, f, g) = 5, 6, 7
3 print a, b, c, d, e

結果顯示 : 1 2 3 5 6 7



上面的動作稱之為 tuple unpacking,將等號右邊的 sequence type object 解開成數個 object 和等號左邊的 name 進行 bind。左邊 tuple 的長度必需和右邊的 item 數目相同。


1 a = 'hello'
2 a, b, c, d, e = a
3 print d, e, a, b, c

結果顯示 : l o h e l



在 multiple assignment 的右邊可以為任何 sequence type。

Dictionary



1 tel = { 'tony': '111234', 988: 'common' }
2 print tel[988], tel['tony']
結果顯示 : common 111234



這為 dictionary (assocative array) 的使用範例。可使用任一 immutable type object 為 key, 用以對映(mapping)指定之 object。


1 a = (1, 2)
2 b = (3, 4)
3 c = (1, 2)
4 d = { a: 'aaa', b: 'bbb' }
5 print d[a], d[b], d[c]

結果顯示 : aaa bbb aaa



tuple 也為 immutable object,所以也可作為 key。因為 a 和 c 所 bind 的 object 為相同 value 的 immutable type object,因此得到的結果是相同的。tuple 為 key 時, 其內容不可包含任何 mutable type object。


1 a = { 'foo': 'aaa', 'boo', 999, 'coo', 887}
2 print a.keys()

結果顯示 : ['boo', 'foo', 'coo']



keys() 為 dictionary 的 method,傳回包含所有 key 的 list object。key 的放置不依其次序。


1 a = { 'aaa': 9999, 'bbb', 8888 }
2 for i in 'aaa', 'bbb', 'ccc':
3 if a.has_key(i):
4 print a[i],

結果顯示 : 9999 8888



has_key() 為 dictionary 的 method function,用以判斷 dictionary 是否包含某 key。


1 a = { 1: 'aaa', 2: 'bbb', 3: 'ccc'}
2 del a[2]
3 b = ['aaa', 'bbb', 'ccc']
4 del b[1]
3 print a, b

結果顯示 : { 1:'aaa', 3:'ccc'} ['aaa', 'ccc']



del 指含可以打斷 object 和 key 之間的 binding,並將 key 從 dictionary 去除。可以將 list 中的 elemnet 去除。

webasp.net