Pass two elements through the generator at the same time

I defined a generator that prints log entries from Elasticsearch:

def gen():
    ....
    for hit in results:
        yield hit

How can I scroll two elements at the same time? Something in the lines:

for one, two in gen():
    ...

Under the two elements, I mean it: A, B, B, C, ..., Y, Z(for the generated list A, B, ..., Y, Z).

+6
source share
3 answers

Answering your updated question, use itertools.teeto create a second iterator, go to the second iterator once and discard the result, then collapse both iterators in pairs with zip.

>>> from itertools import tee
>>> it = iter('abc')
>>> it1, it2 = tee(it)
>>> 
>>> next(it2, None)
'a'
>>> for first, second in zip(it1, it2):
...     first, second
... 
('a', 'b')
('b', 'c')

. , "" ? , .

, . , pairwise itertools docs:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
+6

, . zip(), :

for one, two in zip(gen, gen):
    # do something

:

>>> gen = (x for x in range(5))
>>> for one, two in zip(gen, gen): print(one,two)
... 
0 1
2 3

, timgeb itertools.zip_longest, , , , :

>>> gen = (x for x in range(5))
>>> for one, two in zip_longest(gen, gen): print(one, two)
... 
0 1
2 3
4 None
+6

:

def gen():
    results = [1, 2, 3, 4, 5]
    for i, v in enumerate(results):
        # if i < len()
        if (i + 1) < len(results):
            yield (v, results[i + 1])
        else:
            yield v


output = gen()

for each in output:
    print(each)

:

(1, 2)
(2, 3)
(3, 4)
(4, 5)
5
0

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


All Articles