tuple 可放任意物件,但不可變 ;
tuple用法如下
tupleSample = ("Groucho","Sam")
print(empty_tuple)
emptySample = "Sandy","Paul"
print(empty_tuple)
('Groucho', 'Sam')
('Sandy', 'Paul', 'Rose')
為字元找尋字元為第幾個
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
index = vowels.index('e')
print('The index of e:', index)
index = vowels.index('i')
print('The index of i:', index)
The index of e: 1
The index of i: 2
印出格式
print(type(vowels))
<class 'tuple'>
一次對應多個對應變數,稱為拆包(unpacking)
marx_tuple = ( 'Groucho' , 'Chico' , 'Harpo')
a, b , c = marx_tuple
print(a)
print(b)
print(c)
tuple 值直接對調(SWAP),不用暫存變數
password = 'Hello' ,
icecream = 'Mary' ,
password , icecream = icecream , password
print(password)
print(icecream)
('Mary',)
('Hello',)
使用tuple()函式,轉換成tuple
marx_list = ['Groucho' , 'Chico' , 'Harpo']
print(tuple(marx_list))
('Groucho', 'Chico', 'Harpo')
print(('Groucho' ,)+ ('Chico' , 'Harpo'))
('Groucho', 'Chico', 'Harpo')
用 * 乘號來運算 顯示多筆
('yeah',) * 3
print(('yeah',) * 3)
('yeah', 'yeah', 'yeah')
比較 tuple
a = (7,2)
b = (7,2,9)
a == b
print(a == b)
使用range()
range_tuple = tuple(range(10))
print(type(range_tuple))
print(range_tuple)
print(range_tuple[:5:2])
(0, 2, 4)
List 可放任意物件 ,可變。
List用法如下
t1 = ('one','two','three')
t2 = ('four')
print(id(t1))
print(t1 + t2)
t1 += t2
print(t1)
print(id(t1))
('one', 'two', 'three', 'four')
47210502568192
('one', 'two', 'three', 'four')
47210502433104
tuple 與 串列 比較
tuple 通常可以取代List,但可操作的功能會少很多,且不能修改。
tuple優點: