鱼C论坛

 找回密码
 立即注册
查看: 844|回复: 0

[技术交流] cookbook 1.3

[复制链接]
发表于 2022-1-16 23:49:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

保留最后N个元素

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

一、from collections import deque
  1. def search(lines, pattern, history):
  2.     previous_lines = deque(maxlen=history)
  3.     for line in lines:
  4.         if pattern in line:
  5.             yield line, previous_lines # yield 相当于一个不结束函数的return
  6.         previous_lines.append(line)


  7. if __name__ == '__main__':
  8.     with open("test.txt") as fp:
  9.         for line, pre in search(fp, "python", 3):
  10.             for pline in pre:
  11.                 print(pline, end="")
  12.             print("line", line, end="")
  13.             print('-'*20)
复制代码
  1. # test文本
  2. python
  3. sdasd collections
  4. python  python  python  python
  5. python  python  python  python
  6. sdasd collections python
  7. 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


二、有限队列
  1. q = deque(maxlen=3)  # 队列长度为3
  2. q.append(1)
  3. q.append(2)
  4. q.append(3)
  5. q.append(4)  # 将 1 给挤出队列
  6. print(q)
复制代码
deque([2, 3, 4], maxlen=3)

三、无限队列
  1. q = deque()  # 不指定maxlen
  2. q.append(2)
  3. q.appendleft(1)  # 左边添加 无右添加
  4. q.append(3)
  5. print(q)
  6. print(q.popleft())  # 无参数,无右弹出
复制代码
deque([1, 2, 3])
1

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 21:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表