python - 如何在 python 中生成 'flatten' 生成器?

标签 python recursion iterator python-itertools yield

我在 python 中“展平”一些生成器时遇到问题。这是我的代码:

import itertools as it
test = [[1,2,3],[4,5],[6,7,8]]
def comb(possible):
    if len(possible) != 1:
        for a in possible[0]:
            yield from it.product((a,), comb(possible[1:]))
    else:
        yield from possible[0]
list(comb(test))

这给了我:

[(1, (4, 6)),
(1, (4, 7)),
(1, (4, 8)),
(1, (5, 6)),
(1, (5, 7)),
(1, (5, 8)),
(2, (4, 6)),
(2, (4, 7)),
(2, (4, 8)),
(2, (5, 6)),
(2, (5, 7)),
(2, (5, 8)),
(3, (4, 6)),
(3, (4, 7)),
(3, (4, 8)),
(3, (5, 6)),
(3, (5, 7)),
(3, (5, 8))]

但是,我想要这样的东西:

[(1, 4, 6),
(1, 4, 7),
(1, 4, 8),
(1, 5, 6),
(1, 5, 7),
(1, 5, 8),
(2, 4, 6),
(2, 4, 7),
(2, 4, 8),
(2, 5, 6),
(2, 5, 7),
(2, 5, 8),
(3, 4, 6),
(3, 4, 7),
(3, 4, 8),
(3, 5, 6),
(3, 5, 7),
(3, 5, 8)]

一般来说,该函数应该为我提供遍历列表的所有可能路径的生成器,即 from test[0] -> test[1] -> ... -> test[n] 其中nlen(test)。在这里,它在每一步拾取一个元素。

与以下函数返回的内容类似,只是使用生成器:

def prod(possible):
    if len(possible) != 1:
        b = []
        for i in range(len(possible[0])):
            for x in prod(possible[1:]):
                if len(possible) == 2:
                    b += [[possible[0][i]]+[x]]
                else:
                    b += [[possible[0][i]]+x]
        return b
    else:
        return possible[0]
prod(test)

我尝试了 it.chainit.chain.from_iterable 但似乎无法使其工作。问题是我的“测试”列表的大小和长度是可变的,因此我必须递归地完成整个过程。

编辑:

itertools.product(*test)

正如约翰·科尔曼所指出的那样

最佳答案

这是一种不使用内置函数来计算列表乘积的方法

def product (*iters):
  def loop (prod, first = [], *rest):
    if not rest:
      for x in first:
        yield prod + (x,)
    else:
      for x in first:
        yield from loop (prod + (x,), *rest)
  yield from loop ((), *iters)

for prod in product ("ab", "xyz"):
  print (prod)

# ('a', 'x')
# ('a', 'y')
# ('a', 'z')
# ('b', 'x')
# ('b', 'y')
# ('b', 'z')

在Python中,我们可以使用list构造函数将生成器的输出收集到列表中。请注意,我们还可以计算两个以上输入的乘积,如下所示

print (list (product ("+-", "ab", "xyz")))
# [ ('+', 'a', 'x')
# , ('+', 'a', 'y')
# , ('+', 'a', 'z')
# , ('+', 'b', 'x')
# , ('+', 'b', 'y')
# , ('+', 'b', 'z')
# , ('-', 'a', 'x')
# , ('-', 'a', 'y')
# , ('-', 'a', 'z')
# , ('-', 'b', 'x')
# , ('-', 'b', 'y')
# , ('-', 'b', 'z')
# ]

由于 product 接受可迭代列表,因此任何可迭代输入都可以在产品中使用。它们甚至可以混合使用,如下所示

print (list (product (['@', '%'], range (2), "xy")))
# [ ('@', 0, 'x')
# , ('@', 0, 'y')
# , ('@', 1, 'x')
# , ('@', 1, 'y')
# , ('%', 0, 'x')
# , ('%', 0, 'y')
# , ('%', 1, 'x')
# , ('%', 1, 'y')
# ]

因为 product 被定义为生成器,所以即使在编写更复杂的程序时,我们也能获得很大的灵 active 。考虑这个程序,它找到由整数组成的直角三角形,a Pythagorean triple 。另请注意,product 允许您重复可迭代作为输入,如下面的 product (r, r, r)

所示
def is_triple (prod):
  (a,b,c) = prod
  return a * a + b * b == c * c

def solver (n):
  r = range (1,n)
  for p in product (r, r, r):
    if is_triple (p):
      yield p

print (list (solution in solver (20)))
# (3, 4, 5)
# (4, 3, 5)
# (5, 12, 13)
# (6, 8, 10)
# (8, 6, 10)
# (8, 15, 17)
# (9, 12, 15)
# (12, 5, 13)
# (12, 9, 15)
# (15, 8, 17)

有关更多说明以及了解如何在不使用生成器的情况下执行此操作的方法,请查看 this answer .

关于python - 如何在 python 中生成 'flatten' 生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54296870/

相关文章:

java - 数独递归问题(Java)

c++ - 为什么 C++ 中的 set::end 迭代器取消引用集合中的元素数量?

java-8 - Spliterator:线程安全与否?

Python:这两个 import 语句有什么区别?

Python 一般将数据解析为对象结构

Python Plotly - 如何返回范围 slider 的当前位置?

recursion - Lisp Stack溢出递归函数

python - 将变量指定为列表而不在函数中覆盖它

c++ - 如何获取 std::set 的第一个元素

python - Ctypes:将指针传递给使用sprintf的dll函数时, “Debug assertion failed”(string!= NULL)