Why is the first rejected sample missing after reading a prefix?
takewhile stops on the first false predicate after consuming the element that caused it to stop.
Python example and interpretation
Reading the below-five prefix yields one and three. Eight was inspected to find the boundary, so preserve it explicitly if the next stage needs it.
from itertools import takewhile
s=iter([1,3,8,2])
[list(takewhile(lambda x:x<5,s)),list(s)]Result [[1, 3], [2]]
中文
为什么读取前缀后,首个失败样本也消失了?
takewhile 在谓词首次失败时停止,而触发停止的元素已从输入取出。
Python 算例与适用条件
读小于 5 的前缀得到 1、3,边界值 8 已被检查。若后段还需要 8,要显式保存边界。
from itertools import takewhile
s=iter([1,3,8,2])
[list(takewhile(lambda x:x<5,s)),list(s)]结果 [[1, 3], [2]]