Create a generator that yields values from any number of inner generators

后端 未结 2 1009
轻奢々
轻奢々 2021-01-18 09:34

I have a generator function generate which yields 5 random numbers one at a time. I need to be able to generate the numbers in two ways:

  1. Single g
相关标签:
2条回答
  • 2021-01-18 10:10

    you should use itertools.chain.from_iterable

    return itertools.chain.from_iterable(generate(value) for value in values)
    
    0 讨论(0)
  • 2021-01-18 10:13

    You can specify generator delegation using yield from starting with python-3.3+.

    def get_resource(values=None):
        def resource_generator():
            if values:
                for value in values:
                    yield from generate(value)
            else:
                yield from generate(None)
    
        return resource_generator()
    

    Now,

    >>> list(get_resource([1, 2, 3]))
    [46, 99, 97, 1, 42, 79, 69, 9, 45, 25, 77, 56, 54, 7, 41]
    
    0 讨论(0)
提交回复
热议问题