我在python中使用itertools模块。我发现combination_with_replacement没有给我所有的组合。
>>>import itertools
>>>[list(x) for x in itertools.combinations_with_replacement('AB', 3)]
[['A', 'A', 'A'], ['A', 'A', 'B'], ['A', 'B', 'B'], ['B', 'B', 'B']]
它不会给我['A','B','A']或['B','A','B']。
有谁知道为什么会这样,更重要的是,如何纠正它?
答案 0 :(得分:2)
尝试product
重复3次:
import itertools
print [list(x) for x in itertools.product('AB', repeat=3)]
给出:
[['A','A','A'],['A','A','B'],['A','B','A'],['A' ,'B','B'],['B','A','A'],['B','A','B'],['B','B','A' ],['B','B','B']]
请记住,使用列表理解,您始终可以使用:
ab_str = "AB"
# don't have to use +, can do (x, y, z,)
print [x + y + z for x in ab_str for y in ab_str for z in ab_str]
给出:
['AAA','AAB','ABA','ABB','BAA','BAB','BBA','BBB']