Search code examples
pythonrandomgenerator

Python when generator 'yield' encounter 'random'


Here i want to generate 5 dicts, where 'a' is index 'i', 'b' is a random int between 0 and 5. But result stuck at 'a'=0, it kept generate new c from random.randint(0,5) and 'i' remained the same. how to fix this? thx a lot

def wdg():
    for i in range(5):
        c = random.randint(0,5)
        yield {'a':i,'b':c}

next(wdg())

Solution

  • Assign generator to a variable for example 'generator'. Then each time you call next(generator) one execution will occur, leading to increment i by one and generate random c:

    generator = wdg()
    print(next(generator))