在生成所有可能的组合时 itertools.combinations_with_replacement() 与 itertools.product()?

Tor*_*oal 6 python python-3.x python-3.3

在编写一个查找列表中所有不同组合的程序时,我发现了很多关于使用intertools.product()而不是 的线程intertools.combinations_with_replacement(),就像我一直在做的那样。没有人解释为什么您应该使用 intertools.product。我很想知道这如何影响我的程序输出。

vol*_*ano 6

来自 Python 文档

itertools.product(*iterables[, 重复])

输入可迭代对象的笛卡尔积。

相当于生成器表达式中的嵌套 for 循环。例如,product(A, B) 返回与 ((x,y) for x in A for y in B) 相同的结果。

换句话说:

for x, y in itertools.product(A, B):
Run Code Online (Sandbox Code Playgroud)

取代

for x in A:
    for y in B:
............
Run Code Online (Sandbox Code Playgroud)

编辑:

  • itertolls.combinations_with_replacement()将采用单个可迭代对象并生成其给定长度的元素的所有可能组合;

  • itertools.product()将生成来自多个可迭代对象的值的组合,其中结果元组的元素 0 来自第一个可迭代对象,元素 1 来自第二个可迭代对象,依此类推。

  • 虽然正确并且肯定比当前接受的答案更好,但这并不能回答它与“combinations_with_replacement”相比如何,这是一个明确的问题。 (3认同)