Traversing Python Generator Sequence

Source: Internet
Author: User
Keywords python generator python generator sequence

We can use lists to store data, but when the data is large, creating a list of stored data will take up memory. The generator is a method that does not take up much computer resources.


I have a series of generators: (gen_0, gen_1, ... gen_n)


These generators will create their values lazily, but they are limited and may vary in length.

I need to be able to construct another generator that generates the first element of each generator in order, then the second in turn, and so on, thereby skipping the value of the exhausted generator.

I think this question is similar to taking tuples

((1, 4, 7, 10, 13, 16), (2, 5, 8, 11, 14), (3, 6, 9, 12, 15, 17, 18))
Then iterate over it to produce numbers from 1 to 18 in order.

I am using (genA, genB, genC) to solve this simple example, where the values generated by genA are (1, 4, 7, 10, 13, 16) and the values generated by genB (2, 5, 8, 11, 14) and genC (3, 6, 9, 12, 15, 17, 18).

To solve the simple problem of tuple tuples, if the elements of the tuple are the same length, the answer is very simple. If the variable "a" refers to a tuple, you can use

[i for t in zip(*a) for i in t]
Unfortunately, the length of the items is not necessarily the same, and the zipper technique does not seem to apply to the generator.

So far, my code is very ugly, and I can't find any solution. Help?


solution
You might consider itertools.izip_longest, but if None is a valid value, the solution will fail. This is an example "another generator" that fully meets your requirements and is very clean:

def my_gen(generators):
    while True:
        rez = ()
        for gen in generators:
            try:
                rez = rez + (gen.next(),)
            except StopIteration:
                pass
        if rez:
            yield rez
        else:
            break

print [x for x in my_gen((iter(xrange(2)), iter(xrange(3)), iter(xrange(1))))]

[(0, 0, 0), (1, 1), (2,)] #output
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.