How to use Python iterators correctly

I am trying to use iterators more for the loop, since I heard that it is faster than the indexing loop. One thing I'm not sure about is how to nicely handle the end of a sequence. How can I think it’s used tryand except StopIterationthat looks ugly to me.

To be more specific, suppose we are asked to print a combined sorted list of two sorted lists aand b. I would write the following

aNull = False
I = iter(a)
try:
    tmp = I.next()
except StopIteration:
    aNull = True

for x in b:
    if aNull:
        print x
    else:
        if x < tmp:
            print x
        else:
            print tmp,x
            try:
                tmp = I.next()
            except StopIteration:
                aNull = True

while not aNull:
    print tmp
    try:
        tmp = I.next()
    except StopIteration:
        aNull = True

How would you encode it to make it more accurate?

+3
source share
3 answers

, a b . , next Python 2.6 StopIteration:

def merge(a, b):
    """Merges two iterators a and b, returning a single iterator that yields
    the elements of a and b in non-decreasing order.  a and b are assumed to each
    yield their elements in non-decreasing order."""

    done = object()
    aNext = next(a, done)
    bNext = next(b, done)

    while (aNext is not done) or (bNext is not done):
        if (bNext is done) or ((aNext is not done) and (aNext < bNext)):
            yield aNext
            aNext = next(a, done)
        else:
            yield bNext
            bNext = next(b, done)

for i in merge(iter(a), iter(b)):
    print i

.

def merge(*iterators):
    """Merges a collection of iterators, returning a single iterator that yields
    the elements of the original iterators in non-decreasing order.  Each of
    the original iterators is assumed to yield its elements in non-decreasing
    order."""

    done = object()
    n = [next(it, done) for it in iterators]

    while any(v is not done for v in n):
        v, i = min((v, i) for (i, v) in enumerate(n) if v is not done)
        yield v
        n[i] = next(iterators[i], done)
+8

. I.next(), I.

for tmp in I:
    print tmp

Edited

, itertools. , izip:

merged = []
for x, y in itertools.izip(a, b):
    if x < y:
        merged.append(x)
        merged.append(y)
    else:
        merged.append(y)
        merged.append(x)

, , b , . , , : heapq.merge.

+5

The function sorted works with lists and iterators. This may not be what you want, but the following code works.


a.expand(b)
print sorted(iter(a))

0
source

Source: https://habr.com/ru/post/1779561/


All Articles