← 中文资源

简体中文版本

takewhile 与 dropwhile 按谓词切前缀

dropwhile 跳过开头连续满足条件的元素,takewhile 只保留这段前缀:两者都在第一个不匹配处停止,与 filter 的全量过滤语义完全不同。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:lines、data、scores、head。

使用要点

  • 直接运行文件,输出会带上标签,比如 data:、takewhile:、filter :——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:itertools。 状态都挂在模块顶层:lines、data、scores。

代码示例

from itertools import dropwhile, takewhile

lines = ["# header", "# owner: ci", "", "alpha=1", "beta=2"]

# dropwhile skips the leading run of satisfying items: once the predicate is false, everything else passes through as-is
data = list(dropwhile(lambda line: line.startswith("#") or line == "", lines))
print("data:", data)

scores = [92, 88, 59, 76]

# takewhile keeps only the leading run that satisfies the predicate: it stops entirely the moment 59 shows up
head = list(takewhile(lambda score: score >= 60, scores))
print("takewhile:", head)

# filter skips unqualified items and keeps collecting: different from takewhile's prefix-only semantics
print("filter  :", list(filter(lambda score: score >= 60, scores)))