How to send additional results from a python generator to a user function?

I have a library function (which I cannot change) that takes as an input an iterator that provides a specific type of object. I implemented this input as a generator that parses the text and gives parts of it. I would like to be able to take into account other information found during the analysis of the text.

The comments in the following example give an idea of ​​what I would like to do:

the_text = """1:-
3:-
2:+
4:-
6:+
2:-
4:-
5:+
6:-
7:+"""

def extract_ints(text):
    for line in text.split("\n"):
        fields = line.split(":")
        #<send fields[1] to my_consumer_function>
        yield fields[0]

# Cannot modify this one (actually loaded from library)
def double_ints(num_source):
    """Only wants numbers."""
    for num in num_source:
        yield 2 * int(num)

def my_consumer_function(text):
    for value in double_ints(extract_ints(text)):
        #<receive sign from extract_ints>
        #if sign == "-":
        #    value *= -1
        print(value)

my_consumer_function(the_text)

How can I start sending this information from my generator to my consumer function along with the output of an unmodifiable library function?

+4
source share
1 answer

, , :

from itertools import imap, izip, tee
from operator import itemgetter

def extract_ints(text):
    for line in text.split("\n"):
        fields = line.split(":")
        yield fields[0], fields[1]

def my_consumer_function(text):      
    it1, it2 = tee(extract_ints(text))
    it1 = double_ints(imap(itemgetter(0), it1))
    it2 = imap(itemgetter(1), it2)
    for value, sign in izip(it1, it2):
        if sign == "-":
            value *= -1
        print(value)

Python 3 map zip.

+2

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


All Articles