当前位置:编程学习 > CGI >>

Python 快速入门(二)

答案:原作者: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 去除。

上一个:Python 快速入门(一)
下一个:Python 快速入门(三)

更多图片编程知识:
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,