简体   繁体   中英

Does python have any builtin or standard-library lookahead mechanism for iterators?

In principle it is easy enough to write a wrapper for iterators, that allows arbitrary look-ahead, and some questions have been dedicated to that (eg Using lookahead with generators ).

However, given that pretty much every non-trivial file-parsing would profit from such a facility, it seems like too obvious an oversight for the standard library; Is there really no builtin or standard-library mechanism, that would allow peeking?

Specifically, I usually need peeking that works across function calls: A subfunction should be able to inspect an arbitrary number of upcoming elements, without removing them from the iterator – essentially a queue data type, where the elements are taken lazily from an iterator.

In some cases, collections.deque or itertools.tee can be used to construct workarounds. For the sake of code-readability, they are however unfavorable.

No.


I often find myself using the pairwise Recipe to lookahead...

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):
    ...

Or simply turn your iterable into a Sequence (if it's not already) and use indexed lookups.

for index, item in enumerate(sequence):
    try:
        peek = sequence[index+1]
    except IndexError:
        peek = None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM