高并發(fā)訪問的時代,我們要得到商品或評論的Top 10 ,如果需要去通過查詢數(shù)據(jù)庫下愈,那么顯然是效率低下的。一個解決方案是在內(nèi)存中存放一個固定長度的數(shù)組寞忿,每當新數(shù)據(jù)從上面壓入驰唬, 就有相應數(shù)量的舊數(shù)據(jù)就從下面被頂出
常規(guī)辦法:利用numpy的Array構(gòu)建動態(tài)數(shù)組
import numpy as np
class DynamicArray(object):
"""基于np擴展一個固定長度的動態(tài)數(shù)組"""
def __init__(self, length, name = None, item_type = float):
self.name = name
self._data = np.zeros(length, dtype=item_type)
self._length = length
self._dataSize = 0
def append(self, value):
"""動態(tài)添加數(shù)據(jù)"""
self._data[0:self._length - 1] = self._data[1:self._length]
self._data[-1] = value
self._dataSize += 1
self._dataSize = min(self._dataSize, self._length)
def getData(self):
"""獲取數(shù)據(jù)"""
return self._data
其實,我們可以采用Python內(nèi)建的一個集合模塊
Deques是堆棧和隊列的泛化(名稱發(fā)音為“deck”腔彰,是“雙端隊列”的縮寫)叫编。 Deques支持線程安全,高效的內(nèi)存追加霹抛,并從雙側(cè)出現(xiàn)搓逾,并且在任一方向都具有大致相同的O(1) 性能。
雖然列表 list
對象也支持類似的操作杯拐,但是Deques針對快速固定長度操作進行了優(yōu)化霞篡,并且會導致pop(0)
和 insert(0, v)
操作的O(n)內(nèi)存移動成本,這會改變底層數(shù)據(jù)表示的大小和位置端逼。如果沒有指定maxlen或者是None朗兵,deques可能會增長到任意長度。否則顶滩,deque被限制到指定的最大長度余掖。
一旦固定長度的deque已滿,當添加新項目時礁鲁,相應數(shù)量的項目將從相反的一端被丟棄盐欺。有界長度deques提供類似于Unix中尾部tail
過濾器的功能。它們也可用于跟蹤只有最近的活動感興趣的數(shù)據(jù)池仅醇。 Deque對象支持以下方法:
append(x)
Add x to the right side of the deque.
appendleft(x)
Add x to the left side of the deque.
clear()
Remove all elements from the deque leaving it with length 0.
copy()
Create a shallow copy of the deque.
New in version 3.5.
count(x)
Count the number of deque elements equal to x.
New in version 3.2.
extend(iterable)
Extend the right side of the deque by appending elements from the iterable argument.
extendleft(iterable)
Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.
index(x[, start[, stop]])
Return the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found.
New in version 3.5.
insert(i, x)
Insert x into the deque at position i.
If the insertion would cause a bounded deque to grow beyond maxlen, an IndexError is raised.
New in version 3.5.
pop()
Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.
popleft()
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.
remove(value)
Remove the first occurrence of value. If not found, raises a ValueError.
reverse()
Reverse the elements of the deque in-place and then return None.
New in version 3.2.
rotate(n=1)
Rotate the deque n steps to the right. If n is negative, rotate to the left.
When the deque is not empty, rotating one step to the right is equivalent to d.appendleft(d.pop()), and rotating one step to the left is equivalent to d.append(d.popleft()).
Deque objects also provide one read-only attribute:
maxlen
Maximum size of a deque or None if unbounded.
New in version 3.1.