遍历多个列表时跳过特定列表中的迭代

Skipping an Iteration in a Specific List when Iterating through Multiple Lists

这个问题有点类似于this问题,但不同的是它需要多个列表:

我有三个列表:

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

我按如下方式遍历列表:

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

我想添加一个用以下伪代码表示的条件:

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

我怎样才能做到这一点? itertools 中是否有可用于完成此操作的函数?

假设我正确地解释了你的问题(你想跳到下一个 a 元素,而不重置 [=15] 的 b/c 循环中的偏移量=]),这应该可以解决问题。它不像您喜欢的那样以 itertools 为中心,但它确实有效,而且不应该太慢。据我所知,itertools 没有任何东西可以完全满足您的要求,至少不是开箱即用。大多数函数(islice 是一个典型的例子)只是跳过元素,这仍然会消耗时间。

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

输出:

>>> 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)]