今天要來繼續接著介紹 tuple 的使用方法,包含了 Unpack(拆包),還有取出 tuple 內值的方法,
tupleUnpack 拆包:一次把資料同時指派給多個變數,這個過程稱為 Unpacking 拆包。
tuple 一次給多個變數值color = ('Blue', 'Red', 'Yellow')
a, b, c = color
print(a)
print(b)
print(c)

Unpack 還可以使用 * 來搭配使用
如果變數的數量小於 tuple 的數量,有 * 的變數會把其他的的蒐集起來。
color = ('Blue', 'Red', 'Yellow', 'Orange', 'Green', 'Brown')
(a, b, *c) = color # c 把剩下的元素都帶走
print(a)
print(b)
print(c)

如果是 * 中間的元素,會把前後的先分配好,剩餘的資料都給有 * 的變數
color = ('Blue', 'Red', 'Yellow', 'Orange', 'Green', 'Brown')
(a, *b, c) = color # b 把剩下的元素都帶走
print(a)
print(b)
print(c)

tuple 裡面的元素也可以是另一個 tuple。
color = ('Blue', 'Red', 'Yellow')
color1 = (color, 'Orange', 'Green') # 雙層 tuple
print(color1)

索引值(index)取出 tuple 的值。
tuple ,可以用 tuple[][] 來找出color = ('Blue', 'Red', 'Yellow')
color1 = (color, 'Orange', 'Green')
print(color1[1]) # 取出 color1 的第 1 個元素(起始為 0)
print(color1[-2]) # 取出 color1 的第 -2 個元素(起始為 -1)
print(color1[0]) # 取出 color1 的第 0 個元素,就是 color
print(color1[0][1]) # 取出 color1 的第 0 個元素 color 的第 1 個元素

Range of indexes:取出一組 tuple 的範圍。
color = ('Blue', 'Red', 'Yellow', 'Orange', 'Green', 'Brown')
print(color[2:4]) # 取出 tuple[2] 到 tuple[3] 的元素
print(color[1:]) # 取出 tuple[1] 到最後一個元素
print(color[:4]) # 取出 tuple[0] 到第 3 個元素
print(color[-5:-2]) # 取出 tuple[-5] 到 tuple[-3] 的元素,相當於 tuple[1:4]

使用 tuple 交換兩數。
a = 6
b = 9
print('before a =', a, 'b =', b)
a, b = b, a #等同於 (a, b) = (b, a)
print('after a =', a, 'b =', b)

待續...