假设我们有一个deque用maxlen=3。如果deque已经有3个物品,而当我append有一个新物品时,如何获得将要丢弃的物品?
原因是我想在内存中维护一个仅包含最后N个项目的窗口,并且当该窗口已满并且要丢弃一个项目时,我需要获取该项目并做一些额外的工作。
这是我当前的解决方案:
from collection import deque
MAX_LEN=10
q = deque(maxlen=MAX_LEN)
while True:
if len(q) == MAX_LEN:
discarded = q.popleft()
process(discarded)
q.append(some_var)
Run Code Online (Sandbox Code Playgroud)
这是我能得到的最好的吗?我曾想过使用list切片列表来限制大小/丢弃物品,但这if是不可避免的。使用deque至少我可以O(1)在性能push和popleft操作。
有任何想法吗?
像这样的东西可能对你有用。
def pairwise(iterable, n=2 ):
from itertools import tee, islice, izip
return izip(*(islice(it,pos,None) for pos,it in enumerate(tee(iterable, n))))
for values in pairwise(infinite_iterable_generating_your_values, n=3):
process(values[0])
if breakconditions:
break
Run Code Online (Sandbox Code Playgroud)
成对函数的示例:
print [i for i in pairwise(range(10), n=3)]
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |