1. 程式人生 > >Python3常用資料結構及方法介紹(二)——元組

Python3常用資料結構及方法介紹(二)——元組

二.元組 tuple

1特點:
①元組不可更改
②圓括號
③可重新賦值

>>> tuple0=(1,2,3)
>>> tuple0=(2,3,4,1)
>>> tuple0
(2, 3, 4, 1)

2常用元組操作(與列表類似):
①索引:

>>> tuple1=(1,2,3,4)
>>> tuple1[2]

3

>>> tuple2=('a','b','c','d')
>>> tuple2[0]

‘a’
②分片:

>>> tuple1[0:2]
(1, 2)
>>> tuple2[1:]
('b', 'c', 'd')

③相加:

  >>> tuple1+tuple2
(1, 2, 3, 4, 'a', 'b', 'c', 'd')

④相乘:

>>> tuple1*2
(1, 2, 3, 4, 1, 2, 3, 4)
>>> tuple2*3
('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')

⑤成員資格:

>>> 2 in tuple1
True
>>> if 'c' in tuple2:print('OK')
... 
OK

⑥長度、最小值、最大值:

>>> len(tuple1)
4
>>> len(tuple2)
4
>>> min(tuple1)
1
>>> min(tuple2)
'a'
>>> max(tuple1)
4
>>> max(tuple2)
'd'

⑦刪除列表元素(元組不可更改)
⑧分片賦值(元組不可更改)
3常用元組函式
①count

>>> tuple3=(2,4,1,5,3,8,3,5)
>>> tuple3
(2, 4, 1, 5, 3, 8, 3, 5)
>>> tuple3.count(3)
2

②index

>>> tuple4=('d','a','f','b','k')
>>> tuple4.index('k')
4
>>> (1,2,4,5,7,8).index(5)
3

③tuple

>>> tuple([1,3,4,5,8])
(1, 3, 4, 5, 8)

④append(元組不可更改)
AttributeError: ‘tuple’ object has no attribute ‘append’
⑤extend
AttributeError: ‘tuple’ object has no attribute ‘extend’
⑥insert
AttributeError: ‘tuple’ object has no attribute ‘insert’
⑦pop
AttributeError: ‘tuple’ object has no attribute ‘pop’
⑧remove
AttributeError: ‘tuple’ object has no attribute ‘remove’
⑨reverse(reversed)
AttributeError: ‘tuple’ object has no attribute ‘reverse’
⑩sort(sorted)
AttributeError: ‘tuple’ object has no attribute ‘sort’

一.列表 list(如上節)

三.字串 string

四.字典 dict

未完待續……

如有疑問或補充,請留言!