python 中重复的组合,其中顺序很重要
Combinations with repetition in python, where order MATTERS
来自 python 的文档:https://docs.python.org/2/library/itertools.html#itertools.combinations
参见 combinations_with_replacement:“# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC”
我想使用相同的函数,并生成 "BA"、"CA" 和 "CB"。
itertools.product
绝对是您在这里寻找的方法。正如文档所述,它实际上是一个紧凑的 for 循环; product(A,B)
等同于 ((x, y) for x in A for y in B)
product
将 return 元素的所有组合,特定于顺序,因此 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)
相同。
简而言之:要获得您要查找的结果,请致电 itertools.product('ABC', repeat=2)
。这将按顺序为您提供元组 AA, AB, AC, BA, BB, BC, CA, CB, CC
。
来自 python 的文档:https://docs.python.org/2/library/itertools.html#itertools.combinations
参见 combinations_with_replacement:“# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC”
我想使用相同的函数,并生成 "BA"、"CA" 和 "CB"。
itertools.product
绝对是您在这里寻找的方法。正如文档所述,它实际上是一个紧凑的 for 循环; product(A,B)
等同于 ((x, y) for x in A for y in B)
product
将 return 元素的所有组合,特定于顺序,因此 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)
相同。
简而言之:要获得您要查找的结果,请致电 itertools.product('ABC', repeat=2)
。这将按顺序为您提供元组 AA, AB, AC, BA, BB, BC, CA, CB, CC
。