在python中与重复的组合,其中顺序重要 [英] Combinations with repetition in python, where order MATTERS
问题描述
摘自python的文档: https://docs.python.org/ 2 / library / itertools.html#itertools.combinations
From python's Documentation: https://docs.python.org/2/library/itertools.html#itertools.combinations
请参见groups_with_replacement:#groups_with_replacement('ABC',2)-> AA AB AC BB BC CC
see combinations_with_replacement: "# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
我想使用相同的功能,并生成 BA, CA和 CB。
I'd like to use the same function, with the bonus of generating "BA", "CA", and "CB".
推荐答案
itertools.product
绝对是您在这里寻找的方法。正如文档所述,它实际上是一个紧凑的for循环; product(A,B)
等效于((A中x等于B中y的(x,y))
itertools.product
is definitely the method you're looking for here. As the documentation states, it is effectively a compact for loop; product(A,B)
is equivalent to ((x, y) for x in A for y in B)
产品
将返回其可以组合的所有元素组合(特定于订单),因此 product('ABC','DEF','GHI')
将为您提供 ADG,ADH,ADI,AEG [...] CFI
。如果要包括重复,则设置可选的 repeat
变量。 product(A,repeat = 4)
等效于 product(A,A,A,A)
。同样, product(A,B,repeat = 3)
与 product(A,B,A,B,A,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
. If you want to include repetition, you set the optional repeat
variable. product(A, repeat=4)
is equivalent to product(A,A,A,A)
. Similarly, product(A, B, repeat=3)
is the same as product(A,B,A,B,A,B)
.
简而言之:要获得所需的结果,请调用 itertools.product('ABC', repeat = 2)
。这将按顺序为您提供元组 AA,AB,AC,BA,BB,BC,CA,CB,CC
。
In short: to get the result you're looking for, call itertools.product('ABC', repeat=2)
. This will get you tuples AA, AB, AC, BA, BB, BC, CA, CB, CC
, in order.
这篇关于在python中与重复的组合,其中顺序重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!