How can a one-pass log reader skip a header and take three rows?
islice slices an iterator by nonnegative positions. Moving to the start consumes the skipped items too.
Python example and interpretation
After skipping the header and taking a,b,c, the original iterator points at d. Reopen the source if the header must be read again.
from itertools import islice
s=iter(['header','a','b','c','d'])
[list(islice(s,1,4)),next(s)]Result [['a', 'b', 'c'], 'd']
中文
如何从不能随机访问的日志流跳过表头并读三行?
islice 用非负起止位置从迭代器读取切片,向前跳过的元素同样会被消费。
Python 算例与适用条件
先略过 header 再取 a、b、c,原迭代器随后停在 d。需要回到表头时,须重新打开数据源。
from itertools import islice
s=iter(['header','a','b','c','d'])
[list(islice(s,1,4)),next(s)]结果 [['a', 'b', 'c'], 'd']