Python 庫、技巧

一、namedtuple:用於構建只有少數屬性但無方法的對象

>>> from collections import namedtuple
>>> Card = namedtuple('Card', ['rank', 'suit'])
>>> card = Card(5, 'hearts')
>>> card
Card(rank=5, suit='hearts')

二、bisect:可迭代對象中的插入與查找

import bisect
>>> li
[26, 27, 40, 50, 53, 59, 70, 80, 87, 97]
# 使用bisect的前提是列表有序
# bisect 主要有兩個函數,在不破壞已有排序下,insort 插入與 bisect 尋找插入位置
>>> bisect.insort(li, 30)    
>>> li
[26, 27, 30, 40, 50, 53, 59, 70, 80, 87, 97]
>>> bisect.bisect(li, 35)
3
# 類似的還有 bisect_left、bisect_rigth,insort_left、insort_right
>>> bisect.bisect_left(li, 30)
2
>>> bisect.bisect_right(li, 30)
3
>>> bisect.bisect(li, 30)   # 即 bisect 贊同於 bisect_right
3

三、內容視圖

  • 不復制內容,在數據結構之間共享內存
>>> numbers = array('h', [-2, -1, 0, 1, 2])
>>> numbers
array('h', [-2, -1, 0, 1, 2])
>>> memv = memoryview(numbers)
>>> len(memv)
5
>>> memv[0]
-2
>>> memv_oct = memv.cast('B')  # 轉化爲'B'類型(無符號字符)
>>> memv_oct
<memory at 0x0000000002EB7DC8>
>>> memv_oct.tolist()
[254, 255, 255, 255, 0, 0, 1, 0, 2, 0]
>>> memv_oct[5] = 4
# 因把2個字節的整數的高位字改成4,有符號整數的值就變成了1024
>>> numbers
array('h', [-2, -1, 1024, 1, 2])

三、部分情況下列表的替代

  • 若僅處理數字,數組更爲合適。數組支持可變對象的 pop、insert、extend 等方法,同時還提供文件讀取更快的方法,如 frombytes、tofile
  • 內容視圖:不復制內容,在數據結構之間共享內存
  • 若爲首尾插入操作較多,可考慮使用雙向隊列(collections.deque)
    1. 雙向隊列對兩邊操作會更快,但對中間元素操作會更慢
    2. append 和 popleft 均爲原子操作,在多線程中也可安全操作,無需擔心資源鎖的問題
>>> from collections import deque
>>> dq = deque(range(10), maxlen=10)
>>> dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
# rotate 可將首尾 n 個元素進行移動
>>> dq.rotate(3)    # n>0,右端左移
>>> dq
deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10)
>>> dq.rotate(-3)   # n<0,左端右移
>>> dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
# append 及 extend 均爲尾部操作,appendleft 與 extendleft 對首部操作
# 當插入的元素操作隊列長度時,多出的元素會被刪除
>>> dq.appendleft(-1)
>>> dq
deque([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8], maxlen=10)
>>> dq.extend([11,22,33])
>>> dq
deque([2, 3, 4, 5, 6, 7, 8, 11, 22, 33], maxlen=10)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章