Professional Documents
Culture Documents
W10 tuple元組容器
W10 tuple元組容器
元組
資料儲存容器
• 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 元組的基本操作
• 元組中的元素,可以用索引的方式讀取。例如:
13
3-1 冒號擷取
• 我們可以使用冒號擷取部分的元組。例如:
• 做法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')