a = '''This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is
significant.'''
使用 ''' 或 """ 就不需要在每一行结数时 escape,但 newline 会被包含入 string 内容。
List
1 a = []
2 a[0] = 'aoo'
3 a[1:3] = [10, 11]
4 b = [1, 2, 3, 'foo']
5 print a, b, b[:3], b[1:]
结果显示 : [9, 10, 11] [1, 2, 3, 'foo'] [1, 2, 3] [2, 3, 'foo']
上面是 list 的使用范例。list 是一个 sequence data type, 类於 C/
C++ 的 array, 但 array 是 fixed length 而 list 不是, 其长度是可以随时改变的。行 1 就 bind a 为一个空的 list。 行 2 则指定 index 0 为 'aoo' string object。行 3 为 list 的 slice 的使用范例。 将 index 1 和 index 3 之间的 item(index 1 和 2) 代换成 10 和 11。行 5 的 b[:3] 则相当於 b[0:3], 而 b[1:] 相当於 b[1:4]。list 内的 item 不需是相同的 type, 如上例在一个 list object 里可以同时包含整数和 string 不同 type 的 item。
1 a = [1, 2, 3] + [4, 5, 6]
2 print a
结果显示 : [1, 2, 3, 4, 5, 6]
和 string 一样,list 也可以进行合并的动作(concatenate)。
slice
1 a = [ 1, 2, 3, 4, 5]
2 print a[3], a[3:], a[:2], a[:-1], a[-2]
结果显示 : 4 [4, 5] [1, 2] [1, 2, 3, 4] 4
index 可为负数,负数则从 list 的结束位置往回数。
list 的 index 可以比作下图,每一个 item 指 list 里的一个 object。而 | 则为 item 之间的分界, 其下方则为其 index。
| item 0 | item 1 | item 2 | .... | item n |
0 1 2 3 n n+1
-n -n+1 -n+2 -n+3 -1
当指定 item k (0 <= k < n+1), 则 index 设为 item k 的前一个分界 index k。 当指定 item k ~ item p (0 <= k <= p < n+1) 时,则 slice 指定为 [k:p+1] (意指 index k 和 index p+1 两个分界之间所有的 item) 或 [k:p-n](注: p < n, p - n < 0 为负数)。
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()
9
7
3
1
2
3
4
5
6
4
8
: