简体   繁体   中英

Stuck in python combinations using itertools

I'm using the itertools module in python. I found that combinations_with_replacement does not give me all the combinations.

>>>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']]

It does not give me ['A','B','A'] nor ['B','A','B'].

Does anyone know why is this and, more importantly, how to correct it?

Try product with 3 repeats:

import itertools
print [list(x) for x in itertools.product('AB', repeat=3)]

Gives:

[['A', 'A', 'A'], ['A', 'A', 'B'], ['A', 'B', 'A'], ['A', 'B', 'B'], ['B', 'A', 'A'], ['B', 'A', 'B'], ['B', 'B', 'A'], ['B', 'B', 'B']]

Remember that using list comprehension you can always resort to:

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]

Gives:

['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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