|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
保留最后N个元素
问题描述:
我们希望在迭代或是其他形式的处理过程中,对最后几项记录做一个有限的历史记录统计
一、from collections import dequedef search(lines, pattern, history):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines # yield 相当于一个不结束函数的return
previous_lines.append(line)
if __name__ == '__main__':
with open("test.txt") as fp:
for line, pre in search(fp, "python", 3):
for pline in pre:
print(pline, end="")
print("line", line, end="")
print('-'*20)
# test文本
python
sdasd collections
python python python python
python python python python
sdasd collections python
python collections python
line python <-打印
-------------------- <- 不接起来是因为 line python = "python\n"
python <-1
sdasd collections <-2
line python python python python
--------------------
python <-1
sdasd collections <-2
python python python python <-3
line python python python python <-打印
--------------------
sdasd collections <-1
python python python python <-2
python python python python <-3
line sdasd collections python <-打印
--------------------
python python python python <-1
python python python python <-2
sdasd collections python <-3
line python collections python -------------------- <- 最后一行无换行符
需要注意的是分解的成变量的个数要和原数据的长度一致
name, age, (year, month) = data
name, age, (year, month, day) = data
二、有限队列q = deque(maxlen=3) # 队列长度为3
q.append(1)
q.append(2)
q.append(3)
q.append(4) # 将 1 给挤出队列
print(q)
deque([2, 3, 4], maxlen=3)
三、无限队列q = deque() # 不指定maxlen
q.append(2)
q.appendleft(1) # 左边添加 无右添加
q.append(3)
print(q)
print(q.popleft()) # 无参数,无右弹出
|
|