You are on page 1of 21

資料儲存容器

元組
資料儲存容器
• Python 的資料儲存容器,可以分為
tuple

集合(set) 串列(list)

字典(dict)

2
資料結構基本概念
• Python具有下列4種資料結構:
– 串列(List)→有序集合
– 元組(Tuple)→不可變的有序集合
– 字典(Dict)→無序的鍵值對映
– 集合(Set)→無序且唯一
3-2 串列(list)
• 使用内建函式可以修改、新增、刪除、插入與取出串列元素。
• list5 = ['蘋果', '柳丁', '櫻桃', '葡萄']
• len(list5)
• list5.index('蘋果')
• list5.append('橘子')
• list5.insert(2,'柚子')
• list5.remove('柳丁')
• list5.pop()
• list5.count('櫻桃')

4
3-2 串列(list)
• 使用内建數學函式:
• list6 = [1, 2, 3, 4, 5]
• list6.sort()
• max(list6) # 回傳串列的最大值
• min(list6) # 回傳串列的最小值
• sum(list6) # 回傳總和

5
Ch3 資料儲存容器

6
3-1 元組( tuple )
• 範例3-1-1

7
3-1 元組( tuple )

8
3-1 元組( tuple )

9
3-1 元組( tuple )

10
3-1 元組( tuple )

11
3-1 元組( tuple )

12
3-1 元組的基本操作
• 元組中的元素,可以用索引的方式讀取。例如:

>>> tuple1 = (1, 2, 3, 4, 5)


>>> tuple1[0]
1
>>> tuple1[1]
2
>>> tuple1[-1]
5
>>> tuple1[-3]
3

13
3-1 冒號擷取
• 我們可以使用冒號擷取部分的元組。例如:

>>> tuple1 = (1, 2, 3, 4, 5)


>>> tuple1[1:3]
(2, 3) # 擷取索引1~3的元組
>>> tuple1[:3]
(1, 2, 3) # 擷取索引0~2的元組
>>> tuple1[2:]
(3, 4, 5) # 擷取索引2~4的元組
3-1 元組運算
• Python的運算子,可以用來對元組進行運算。例如:

>>> tuple1 = (1, 2, 3)


>>> tuple2 = (4, 5)
>>> tuple3 = tuple1 + tuple2
>>> tuple3
(1, 2, 3, 4, 5)
>>> tuple4 = tuple1 * 3
>>> tuple4
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> tuple1 != tuple2
True
>>> tuple1 == tuple2
False
3-1 元組的内建函式

>>> tuple1 = (1, 2, 3, 4, 5)


>>> tuple1.count(2) # 回傳2的元素個數
1
>>> tuple1.index(3) # 回傳3的索引
2
3-1 元組的内建函式

>>> tuple2 = ('Alice', 'Bob', 'John', 'Mary', 'Nancy')


>>> tuple2.count('Bob') # 回傳Bob的元素個數
1
>>> tuple2.index('Mary') # 回傳Mary的索引
3
3-1 元組的優點
• 執行速度比list快
• 儲存在Tuple的資料比較安全
• list和tuple可以互換

• game_tuple = (“籃球”, “足球”, “棒球”, “排球")


• game_list = [“籃球”, “足球”, “棒球”, “排球“]
• a_list = list(game_tuple)
• a_tuple = tuple(game_list)
• print(a_list)
• print(a_tuple)
課堂練習1
• 元組game_tuple有(“籃球”, “足球”, “棒球”, “排球”)。
• 把足球從元組移除。

• 做法1:
• 1. 切片
• 2. 結合
課堂練習1
• 元組game_tuple有(“籃球”, “足球”, “棒球”, “排球”)。
• 把足球從元組移除。

• 做法2:
• 1. 元組轉換串列
• 2.串列轉成元組
課堂練習2
• 把字串“This is Python”轉換成元組。

執行結果:
('T', 'h', 'i', 's', 'i', 's', 'P', 'y', 't', 'h', 'o', 'n')

You might also like