Skip to content

Instantly share code, notes, and snippets.

@istar0me
Created October 3, 2018 17:33
Show Gist options
  • Save istar0me/d228c4ebed35b25d2d6f613f0d38a74a to your computer and use it in GitHub Desktop.
Save istar0me/d228c4ebed35b25d2d6f613f0d38a74a to your computer and use it in GitHub Desktop.

C4 序列(Sequence)

  • 不可變
    • String
    • Tuple
    • Byte
  • 可變
    • List
    • ByteArray

4.1.1 序列與迭代器

  • 先建立一個 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

4.1.2 建立序列資料

  • 序列物件是可迭代者(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)

4.1.3 序列元素及操作

  • 語法:
序列型別[index]
  • 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment