特性
- Ordered sequence of data (有順序的)
- Immutable (不可更改)
- Iterable (可疊代的)
Tuple建立
# Tuple用()將資料包住, 且資料可以任一型態
x = ()
print(x) #()
number = 5, #必須要加逗點
print(number) #(5, )
number = (5, )
print(number) #(5, )
number = 1, 2, 3
print(number) #(1, 2, 3)
number = (1, 2, 3)
print(number) #(1, 2, 3)
#List轉Tuple
number = [1, 2, 3]
print(tuple(number)) #(1, 2, 3)
#String轉Tuple
score ='A++B'
print(tuple(score)) #('A', '+', '+', 'B')
#Iterable (可疊代的)
numbers = tuple(range(5))
print(numbers) #(0, 1, 2, 3, 4)
#用Type去檢查資料型態
print(type(number)) # <class 'tuple'>
Tuple Methods
#元素(elements)有幾個
tuple1 = (1, 2, 3, 4)
print(len(tuple1)) # 4
#取出指定index的元素
print(tuple1[2]) # 3
print(tuple1[:2]) #(1, 2)
print(tuple1[0:2]) #(1, 2)
#不可更改tuple的內容
tuple1[2] = 'a'
print(tuple1) # TypeError: 'tuple' object does not support item assignment
#不可刪除tuple的內容
tuple1 = (1, 2, 3, 4)
del tuple1[2] # TypeError: 'tuple' object does not support item assignment
#更改tuple內的list值
tuple2 = ([1, 2, 3, 4], 'aaa')
tuple2[0][1] = 5
print(tuple2) #([1, 5, 3, 4], 'aaa')
#計算元素出現的次數
tuple3 = (1, 2, 3, 4, 1, 1, 2, 2, 2)
print(tuple3.count(2)) # 4
#用index找出元素的位置
tuple4 = (1, 2, 3, 4, 5, 6)
print(tuple4.index(6)) # 5
Packing and Unpacking
#Packing and Unpacking
x = (a, b, c, d) #Packing
y1, y2, y3, y4 = x #Unpacking
# Packing first, then unpacking
x = 25
y = 10
x, y = y, x
print(x, y) #10 25