1. 程式人生 > 實用技巧 >4. 元組型別

4. 元組型別

1. 作用

按照索引/位置存放多個值,只用於讀,不用於改

2. 定義

t = (1,1.3,'aaa')	#t = tuple((1,1.3,'aaa'))
print(t,type(t))

2.1 單獨一個括號,代表包含的意思

x = (10)	#單獨一個括號,代表包含的意思
print(x,type(x))

2.2 如果元組中只有一個元素,必須加逗號

x = (10,)	#如果元組中只有一個元素,必須加逗號
print(x,type(x))
t = (1,1.3,'aaa')	#t = (0->值1的記憶體地址,1->值1.3的記憶體地址,2->值'aaa'的記憶體地址,)
#只要元組內元素的記憶體地址沒變,元組就是不可變

2.3 元組不能改,指的是不能改裡面的記憶體地址

t = (1,[11,22])
print(t,id(t[0]),id(t[1]))
t[1][0] = 33		# 元組內的列表的元素還是可以改的
print(t,id(t[0]),id(t[1]))

(1, [11, 22]) 2038884272 59297864
(1, [33, 22]) 2038884272 59297864

3. 型別轉換

print(tuple('hello'))
print(tuple([1,2,3]))
print(tuple({'name':egon,'age':18}))

4. 內建方法

4.1 按照索引取值(正向取值+反向取值)只能取

t = (111,'egon','hello')

正向取值

print(t[0])

反向取值

print(t[-1])

4.2 切片(顧頭不顧尾,步長)

t=('aa','bbb','cc','dd','eee')
print(t[0:3])
print(t[::-1])

('aa', 'bbb', 'cc')
('eee', 'dd', 'cc', 'bbb', 'aa')

4.3 長度

t=('aa','bbb','cc','dd','eee')
print(len(t))

5

4.4 成員運算 in 與 not in

判斷一個子字串是否存在於一個大字串中

t=('aa','bbb','cc','dd','eee')
print('aa' in t)

True

4.5 迴圈

t=('aa','bbb','cc','dd','eee')
for x in t:
    print(x)
    
aa
bbb
cc
dd
eee

5. index 和 count補充:

5.1 index:找出該字串在元組中的索引位置,找不到就會報錯

t=(2,3,111,111,111,111)
print(t.index(111))
print(t.index(1111111111))

2
ValueError: tuple.index(x): x not in tuple

5.2 count:統計該字串在元組中出現的次數

t=(2,3,111,111,111,111)
print(t.count(111))

4