Methods for List
1 a = []
2 a.append(1)
3 a.append(2)
4 a.insert(1, 3)
5 print a
结果显示 : [1, 3, 2]
上面是 list 的 append() 和 insert() 两个 method 的使用范例,append 用以新增一个 item 到 list 的最後面。 insert 用以在指定的位置插入一个新的 item。行 4即在 list 的 index 1 的位置(即 item 0 和 item 1 之间)插入一个新 item。
1 a = [1, 3, 2]
2 a.sort()
3 print a,
4 a.reverse()
5 print a
结果显示 : [1, 2, 3] [3, 2, 1]
sort() method 能将 list 进行从小到大的排序,reverse() method 则进行从大至小的反向排序。
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

