简体   繁体   中英

Python-for returning a generator of sequences

I have to generate a function which takes any number of sequences and return a list of tuples. I have tried writing code for generating tuples one by one through generators from the list by using the following code:

>>> gen1 = [(x,y) for x in range(3) for y in range(4)]
>>> gen1
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
>>> iter1 = iter(gen1)
>>> iter1.next()
>>> def gen3():
...     yield iter1.next()
...
>>> next(gen3())

Which is giving the tuples. But I need to apply the same code in the following function which contains many sequences of parameters:

def generator_zip(seq1, seq2, *more_seqs):

How can i use the above mentioned code in this function??

I think itertools.product is what you are looking for

import itertools

print list(itertools.product(range(3), range(4)))

>> [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), 
>> (2, 0), (2, 1), (2, 2), (2, 3)]

print list(itertools.product(range(2), range(3), range(4)))

>> [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), 
>> (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), 
>> (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), 
>> (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]

Note that itertools functions always return generators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM