Python Tuple -本篇會介紹Tuple的3種基本應用方法 – Tuple初始化,Tuple切片, Tuple for迴圈
注意事項:
- Tuple是有次序的, 不能再改變
- Tuple內的值能重覆
- Tuple內的值不能改變
Let’s Start!
方法 | 例子: |
初始化 | lst = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’) print(lst) # (‘John’, ‘Peter’, ‘Mary’, ‘Marks’) |
切片 Slice 1 | lst1 = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’); print(lst1[2:4]) # (‘Mary’, ‘Marks’) |
切片 Slice 2 | lst1 = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’); print(lst1[:4]) # (‘John’, ‘Peter’, ‘Mary’, ‘Marks’) |
切片 Slice 3 | lst1 = [‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’]; print(lst1[2:]) # (‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’) |
切片 Slice 4 | lst1 = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’); print(lst1[-2:]) # (‘Groden’, ‘Guru’) |
切片 Slice 5 | lst1 = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’); print(lst1[:-4]) # (‘John’, ‘Peter’, ‘Mary’) |
切片 Slice 6 | lst1 = (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’); print(lst1[:]) # (‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Kim’, ‘Groden’, ‘Guru’) |
for迴圈 | lst1 = (‘John’, ‘Peter’, ‘Mary’); for x in lst1: print(x) # John # Peter # Mary |
(等如) | |
lst1 = (‘John’, ‘Peter’, ‘Mary’); [print(x) for x in lst1] # John # Peter # Mary |
相關頁面
Python List – 學會List的9種基本應用方法 – 初始化, 加入值, 插入值, 追加值, 更新值, 刪除值, 清除所有值, 切片,排序, for迴圈
Python Set – 學會Set的6種基本應用方法 – 初始化, 加入值, 加入多個值, 刪除值, 清除所有值, for迴圈
Python Dictionary – 學會Dictionary的5種基本應用方法 – 初始化, 加入值, 更新值, 刪除值, foreach迴圈
參考資料: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences