大马强 发表于 2022-1-16 23:49:10

cookbook 1.3


保留最后N个元素
问题描述:
        我们希望在迭代或是其他形式的处理过程中,对最后几项记录做一个有限的历史记录统计

一、from collections import deque
def 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
pythonpythonpythonpython
pythonpythonpythonpython
sdasd collections python
python collections python
line python<-打印
-------------------- <- 不接起来是因为 line python = "python\n"
python <-1
sdasd collections <-2
linepythonpythonpythonpython
--------------------
python <-1
sdasd collections <-2
pythonpythonpythonpython <-3
line pythonpythonpythonpython <-打印
--------------------
sdasd collections <-1
pythonpythonpythonpython <-2
pythonpythonpythonpython <-3
line sdasd collections python <-打印
--------------------
pythonpythonpythonpython <-1
pythonpythonpythonpython <-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(, maxlen=3)
三、无限队列
q = deque()# 不指定maxlen
q.append(2)
q.appendleft(1)# 左边添加 无右添加
q.append(3)
print(q)
print(q.popleft())# 无参数,无右弹出
deque()
1
页: [1]
查看完整版本: cookbook 1.3