python進階(資料結構和演算法[1])
將序列分解為單獨的變數
>>> p = (4,5) # 通過賦值分解元組或序列>>> x,y = p>>> x4>>> y5>>> data = ['ACME', 50, 91.9, (2000,1,1)]>>> name, shares, prices, date = data>>> name'ACME'>>> date(2000, 1, 1)>>> name, shares, prices, (year, month, day) = data>>> prices91.9>>> month1>>> day1>>> string = "hello" #只要對象是可迭代的,就可以進行分解操作>>> a, b, c, d, e = string>>> a'h'>>> b'e'>>> e'o'>>> name, _, prices, _ = data #_表示不感興趣的項>>> name'ACME'>>> prices91.9>>> _(2000, 1, 1)>>> name, _, prices, _ , outbound= data # 解包元素不匹配Traceback (most recent call last): File "", line 1, in name, _, prices, _ , outbound= dataValueError: need more than 4 values to unpack
從任意長度的可迭代對象中分解元素
>>> *trailing, current = [12, 23, 34, 45, 56, 67, 78, 89]>>> current89>>> trailing # 使用“*運算式”進行分解匹配[12, 23, 34, 45, 56, 67, 78]>>> a, b, *, d = [12, 34, 45, 56, 67,89]SyntaxError: invalid syntax>>> a, b, *c, d = [12, 34, 45, 56, 67,89]>>> a12>>> b34>>> c[45, 56, 67]>>> d89>>> line = 'nobody:*:-2:user:/home'>>> uname, *others, path = line.split(':')>>> uname'nobody'>>> path'/home'
對於分解位置或者任意長度的可迭代對象,這樣再合適不過了。對於固定的組件或者模式(如,元素2以後的都是電話號碼,但是電話號碼的數量未知),使用星號運算式可以方便快捷的分解。
儲存最後N個元素
#使用collections中的deque實現from collections import dequed = deque()d.append('1')d.append('2')d.append('3')len(d) # 3d[0] # 1d[-1] # 3d = deque('12345')len(d) # 5d.popleft() # 1d.pop() # 5d # deque(['2', '3', '4'])#我們還可以限制deque的長度:d = deque(maxlen=30)#當限制長度的deque增加超過限制數的項時, 另一邊的項會自動刪除:d = deque(maxlen=2)d.append(1)d.append(2) # deque(['1', '2'])d.append(3) # deque(['2', '3']) | append(...) | Add an element to the right side of the deque. | | appendleft(...) | Add an element to the left side of the deque. | | clear(...) | Remove all elements from the deque. | | count(...) | D.count(value) -> integer -- return number of occurrences of value | | extend(...) | Extend the right side of the deque with elements from the iterable | | extendleft(...) | Extend the left side of the deque with elements from the iterable | | pop(...) | Remove and return the rightmost element. | | popleft(...) | Remove and return the leftmost element. | | remove(...) | D.remove(value) -- remove first occurrence of value. | | reverse(...) | D.reverse() -- reverse *IN PLACE* | | rotate(...) | Rotate the deque n steps to the right (default n=1). If n is negative, | rotates left.