【问题标题】:Skipping an Iteration in a Specific List when Iterating through Multiple Lists遍历多个列表时跳过特定列表中的迭代
【发布时间】:2022-01-19 08:41:57
【问题描述】:

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

我有三个列表:

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

【问题讨论】:

  • 可以用两个游标来完成循环。你坚持只在 itertools 中使用函数吗?
  • 是的,我必须使用 itertools 来解决这个问题。

标签: python for-loop iteration itertools more-itertools


【解决方案1】:

假设我正确地解释了您的问题(您想跳到下一个 a 元素,而不重置 product(a, b, c)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)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2016-01-10
    • 2019-01-25
    • 2020-11-23
    相关资源
    最近更新 更多