2

这个问题有点类似于这个问题,但不同之处在于它需要多个列表:

我有三个列表:

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 中是否有可用于完成此任务的函数?

4

1 回答 1

1

假设我正确地解释了你的问题(你想跳到下一个元素,而不重置/循环中a的偏移量),这应该可以解决问题。它不像你可能喜欢的那样专注于 itertools,但它确实有效,而且不应该太慢。据我所知, itertools 没有任何东西可以完全满足您的要求,至少不是开箱即用。大多数函数(作为一个主要例子)只是跳过元素,这仍然会消耗时间。bcproduct(a, b, c)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)]
于 2021-12-16T09:11:03.817 回答