简体   繁体   English

与python中的重复组合,其中顺序很重要

[英]Combinations with repetition in python, where order MATTERS

From python's Documentation: https://docs.python.org/2/library/itertools.html#itertools.combinations来自 python 的文档: https : //docs.python.org/2/library/itertools.html#itertools.combinations

see combinations_with_replacement: "# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"见组合_with_replacement:“#组合_与替换('ABC',2)--> AA AB AC BB BC CC”

I'd like to use the same function, with the bonus of generating "BA", "CA", and "CB".我想使用相同的功能,附带生成“BA”、“CA”和“CB”的奖励。

itertools.product is definitely the method you're looking for here. itertools.product绝对是您在这里寻找的方法。 As the documentation states, it is effectively a compact for loop;正如文档所述,它实际上是一个紧凑的 for 循环; product(A,B) is equivalent to ((x, y) for x in A for y in B) product(A,B)等价于((x, y) for x in A for y in B)

product will return every combination of elements that it can, order-specific, so product('ABC', 'DEF', 'GHI') will get you ADG, ADH, ADI, AEG [...] CFI . product将返回它可以的元素的每个组合,特定于订单,因此product('ABC', 'DEF', 'GHI')将为您提供ADG, ADH, ADI, AEG [...] CFI If you want to include repetition, you set the optional repeat variable.如果要包括重复,请设置可选的repeat变量。 product(A, repeat=4) is equivalent to product(A,A,A,A) . product(A, repeat=4)等价于product(A,A,A,A) Similarly, product(A, B, repeat=3) is the same as product(A,B,A,B,A,B) .同样, product(A, B, repeat=3)product(A,B,A,B,A,B)

In short: to get the result you're looking for, call itertools.product('ABC', repeat=2) .简而言之:要获得您正在寻找的结果,请调用itertools.product('ABC', repeat=2) This will get you tuples AA, AB, AC, BA, BB, BC, CA, CB, CC , in order.这将按顺序为您提供元组AA, AB, AC, BA, BB, BC, CA, CB, CC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM