0

this is the code I have so far:

I call the generator function from the same class

g = self.gen(infile)

I want to iterate g

for line in infile:
    ...
    numb, c1, winner, c2, scorerTimes = next(g)

but after a bit of debugging, I found that g can only be iterated once

This is my generator function

def gen(self, infile):
    values = []
    winner = ""
    line = infile.readline()
    while not(line.startswith("(")):
        line = infile.readline()
    while True:
        m = re.search("(\d+)\)\s\w+\s\w+/+\d+\s+\d+:\d+\s+(\w+)\s+(\d+)-(\d+).[^)]+\)\s+(\w+)", line)

        line = infile.readline()
        n = re.findall("(\w\s*\w+)\s(\d+)", line)
        if int(m.group(3)) > int(m.group(4)):
            winner = m.group(2)
        else:
            winner = m.group(5)
        yield m.group(1), m.group(2), winner, m.group(5), n

Am I writing the generator function wrong? This is my first time working with generators, so I'm a little confused.

gcourtet
  • 74
  • 2
  • 10
  • Please refer to this answer: https://stackoverflow.com/a/519653/5397845 – Swadhikar Aug 08 '18 at 15:10
  • You could also use [`itertools.cycle`] https://docs.python.org/3/library/itertools.html#itertools.cycle on your generator – c2huc2hu Aug 08 '18 at 15:14
  • Yes, most iterators including generators (and file objects for that matter) are single pass. If you want to go over the data again, then put itnina list – juanpa.arrivillaga Aug 08 '18 at 15:37

0 Answers0