python 是否有针对迭代器的任何内置或标准库先行机制?
Does python have any builtin or standard-library lookahead mechanism for iterators?
原则上,为迭代器编写一个包装器很容易,它允许任意向前看,并且一些问题专门针对此(例如 Using lookahead with generators)。
但是,考虑到几乎所有重要的文件解析都可以从这样的工具中获益,这似乎是对标准库的明显疏忽;真的没有 内置或标准库 允许偷看的机制吗?
具体来说,我通常需要跨函数调用的窥视:子函数应该能够检查任意数量的即将到来的元素,而无需将它们从迭代器中移除——本质上是一种队列数据类型,其中的元素是惰性获取的从一个迭代器。
在某些情况下,collections.deque
或 itertools.tee
可用于构造解决方法。但是为了代码的可读性,它们是不利的。
没有
我经常发现自己使用 pairwise
Recipe 来预测...
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for item, peek in pairwise(iterable):
...
或者简单地将您的可迭代对象转换为一个序列(如果它还没有)并使用索引查找。
for index, item in enumerate(sequence):
try:
peek = sequence[index+1]
except IndexError:
peek = None
原则上,为迭代器编写一个包装器很容易,它允许任意向前看,并且一些问题专门针对此(例如 Using lookahead with generators)。
但是,考虑到几乎所有重要的文件解析都可以从这样的工具中获益,这似乎是对标准库的明显疏忽;真的没有 内置或标准库 允许偷看的机制吗?
具体来说,我通常需要跨函数调用的窥视:子函数应该能够检查任意数量的即将到来的元素,而无需将它们从迭代器中移除——本质上是一种队列数据类型,其中的元素是惰性获取的从一个迭代器。
在某些情况下,collections.deque
或 itertools.tee
可用于构造解决方法。但是为了代码的可读性,它们是不利的。
没有
我经常发现自己使用 pairwise
Recipe 来预测...
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for item, peek in pairwise(iterable):
...
或者简单地将您的可迭代对象转换为一个序列(如果它还没有)并使用索引查找。
for index, item in enumerate(sequence):
try:
peek = sequence[index+1]
except IndexError:
peek = None