| >>> (1, 'Justin', 93) (1, 'Justin', 93) >>> 1, 'Justin', 93 (1, 'Justin', 93) >>> data = (1, 'Justin', 93) >>> data[0] 1 >>> data[0:2] (1, 'Justin') >>> data[0:] (1, 'Justin', 93) >>> for elem in data: ... print(elem) ... 1 Justin 93 >>> (1, 'Justin', 93) + (2, 'momor', 99) (1, 'Justin', 93, 2, 'momor', 99) >>> (1, 'Justin', 93) * 2 (1, 'Justin', 93, 1, 'Justin', 93) >>> |
串列中的索引特性、切片運算、for迴圈迭代等操作,只要不變動Tuple的內容,都可以直接在Tuple在上運作。
如果你要建立單一元素的Tuple,記得不要僅使用括號,而必須在單一元素後加上一個逗號,以免被認定為數值等其它型態。例如:
| >>> (1) 1 >>> (1,) (1,) >>> tuple([1]) (1,) >>> tuple([1, 2]) (1, 2) >>> |
你也可以使用tuple來建立Tuple,tuple接受可迭代(iterable)物件(例如串列)作為建構Tuple之用。
由於Tuple的內容是不能變動的,所以你不能對它作變更操作,例如排序,若你想要排序Tuple,則必須先取得當中元素、排序後重新建構Tuple。例如:
| >>> t1 = (3, 6, 1, 2, 7) >>> l1 = list(t1) >>> l1.sort() >>> t1 = tuple(l1) >>> t1 (1, 2, 3, 6, 7) >>> |
Tuple的內容不可變動,指的是不能變動每個索引所參考的物件,而不是指物件本身不能變動。例如:
| >>> t = ([1, 2], [3, 4]) >>> t ([1, 2], [3, 4]) >>> t[0] = [10, 20] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> t[0][0] = 10 >>> t[0][1] = 20 >>> t ([10, 20], [3, 4]) >>> |
上例中,打算指定Tuple索引0為新的串列物件是不可行的,但t[0][0]指的是改變索引0處的串列索引0的元素,同樣的t[0][1]指的是改變索引0處的串列索引1的元素,也就是相當於:
| >>> t = ([1, 2], [3, 4]) >>> l = t[0] >>> l[0] = 10 >>> l[1] = 20 >>> t ([10, 20], [3, 4]) >>> |
Tuple的內容,可以同時指定給多個變數。例如:
| >>> x, y = 1, 2 >>> x 1 >>> y 2 >>> t = (10, 20) >>> x, y = t >>> x 10 >>> y 20 >>> x, y = y, x >>> x 20 >>> y 10 >>> |
注意x, y = y, x該行,實際上就等於在作交換(Swap)的動作,由於Tuple指定的特性,使得交換的動作在Python中並不需要暫存變數。
事實上,串列、集合,都可以用類似的方式來指定:
| >>> [x, y] = [1, 2] >>> x 1 >>> y 2 >>> x, y = [1, 2] >>> x 1 >>> y 2 >>> (x, y) = [1, 2] >>> x 1 >>> y 2 >>> x, y = {1, 2} >>> x 1 >>> y 2 >>> x, y, z = 'Joe' >>> x 'J' >>> y 'o' >>> z 'e' >>> |
在Python 3中,還有個擴充的指定方式:
| >>> s = [1, 2, 3, 4, 5] >>> a, *b = s >>> a 1 >>> b [2, 3, 4, 5] >>> *a, b = s >>> a [1, 2, 3, 4] >>> b 5 >>> *a, b, c = s >>> a [1, 2, 3] >>> b 4 >>> c 5 >>> a, *b, c = s >>> a 1 >>> b [2, 3, 4] >>> c 5 >>> |
你可以在左邊的變數指定一個*,未指定的變數會被指定一個值,而剩餘的元素會被指定給*所標註的變數。
沒有留言:
張貼留言