- 先建立一個 list 物件名為 data
- 以
iter()
函式將 data 轉成迭代器
- 無元素可讀的時候並不會停止,他會引發「StopIteration」的異常處理
>>> data = [22, 45, 14] # list
>>> num = iter(data) # 轉成迭代器物件
>>> type(num)
<type 'listiterator'>
>>> next(num) # 回傳下一個元素
22
>>> next(num); next(num)
45
14
>>> next(num) # 無元素可讀,回傳錯誤
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
- 序列物件是可迭代者(Iterable),可迭代物件能使用 for 迴圈讀取
- 可搭配
- 可利用索引(index)取得序列中儲存的元素 (C4.1.3)
- 支援
in
/not in
成員運算子,用來判斷某個元素是否(不)隸屬序列物件 (C4.1.3)
- 內建函式
len()
、max()
和min()
能取得長度或大小 (C4.1.4)
- 字串也是序列型別的一種
>>> number = [12, 14, 16] # 我是 list
>>> data = ('Mary', 'Eric', 'Jonson') # 我是 Tuple
>>> word = 'Hello Python' # 我是字串
>>> type(number)
<type 'list'>
>>> type(data)
<type 'tuple'>
>>> type(word)
<type 'str'> # 這邊並非全名 string
- list : 存放同性質的資料
- tuple : 存放異性質的資料
>>> number = [11, 12]
>>> data = (1, 'Mark', 78)
- index(offset) : 偏移量,左邊從 0 開始,右邊則由 -1 開始
元素 |
Jan |
Feb |
Mar |
Apr |
索引編號 |
0 |
1 |
2 |
3 |
索引編號 |
-4 |
-3 |
-2 |
-1 |
>>> tp = 25, 36, 77
>>> tp[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range