Issue
If I use itertools.product
with two lists, the nested for loop equivalent always cycles the second list first:
>>> from itertools import product
>>> list(product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
But for some use cases I might want these orders to be alternating, much like popping the first items off each list, without actually popping them. The hypothetical function would first give [1, 4], then [2, 4] (1 popped), and then [2, 5] (4 popped), and then [3, 5], and finally [3, 6].
>>> list(hypothetical([1,2,3], [4,5,6]))
[(1, 4), (2, 4), (2, 5), (3, 5), (3, 6)]
The only method I can think of is yielding in a for loop with a "which list to pop from next" flag.
Is there a built-in or library method that does this? Will I have to write my own?
Solution
import itertools
L1 = [1, 2, 3]
L2 = [4, 5, 6]
print list(zip(itertools.islice((e for e in L1 for x in (1, 2)), 1, None), (e for e in L2 for x in (1, 2))))
Answered By - Ignacio Vazquez-Abrams
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.