Home > front end >  Skipping an Iteration in a Specific List when Iterating through Multiple Lists
Skipping an Iteration in a Specific List when Iterating through Multiple Lists

Time:12-16

This question is somewhat similar to this question, but different in that it entails multiple lists:

I have three lists:

a = [1, 2, 3, 4, 5, 6, 7]
b = ['ball', 'cat', 'dog', 'elephant', 'baboon', 'crocodile']
c = [6, 3, 5, 4, 3, 2, 1]

I am iterating through the list as follows:

for (x, y, z) in itertools.product(a, b, c):
  print("The combination is: "   str(x)   ", "   y    ", " str(z))

I would like to add a condition which is expressed in the following pseudo-code:

for (x, y, z) in itertools.product(a, b, c):
  if x != z:
     print("The combination is: "   str(x)   ", "   y    ", " str(z))
  if x == z:
     skip to the next element in list "a" without skipping elements of "b" & "c" # this is pseudo code

How could I accomplish this? Is there a function in itertools that could be used to accomplish this?

CodePudding user response:

Assuming I'm interpreting your question correctly (you want to skip to the next a element, without resetting the offset in the b/c cycle of product(a, b, c)), this should do the trick. It isn't as itertools-focused as you may like, but it does work, and shouldn't be too slow. As far as I'm aware, itertools doesn't have anything that will do quite what you're asking, at least not right out of the box. Most functions (islice being a prime example) just skip over elements, which still consumes time.

from itertools import product

def mix(a, b, c):
    a_iter = iter(a)
    for x in a_iter:
        for y, z in product(b, c):
            while x == z:
                x = next(a_iter)
            yield x, y, z

Output:

>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> b = ['ball', 'cat', 'dog', 'elephant', 'baboon', 'crocodile']
>>> c = [6, 3, 5, 4, 3, 2, 1]
>>> pprint(list(mix(a, b, c)))
[(1, 'ball', 6),
 (1, 'ball', 3),
 (1, 'ball', 5),
 (1, 'ball', 4),
 (1, 'ball', 3),
 (1, 'ball', 2),
 (2, 'ball', 1),
 (2, 'cat', 6),
 (2, 'cat', 3),
 (2, 'cat', 5),
 (2, 'cat', 4),
 (2, 'cat', 3),
 (3, 'cat', 2),
 (3, 'cat', 1),
 (3, 'dog', 6),
 (4, 'dog', 3),
 (4, 'dog', 5),
 (5, 'dog', 4),
 (5, 'dog', 3),
 (5, 'dog', 2),
 (5, 'dog', 1),
 (5, 'elephant', 6),
 (5, 'elephant', 3),
 (6, 'elephant', 5),
 (6, 'elephant', 4),
 (6, 'elephant', 3),
 (6, 'elephant', 2),
 (6, 'elephant', 1),
 (7, 'baboon', 6),
 (7, 'baboon', 3),
 (7, 'baboon', 5),
 (7, 'baboon', 4),
 (7, 'baboon', 3),
 (7, 'baboon', 2),
 (7, 'baboon', 1),
 (7, 'crocodile', 6),
 (7, 'crocodile', 3),
 (7, 'crocodile', 5),
 (7, 'crocodile', 4),
 (7, 'crocodile', 3),
 (7, 'crocodile', 2),
 (7, 'crocodile', 1)]
  • Related