Pregunta

Hey I have a list where I would want to get all the different permutations of it i.e [A,B,C].

I want all different combinations of it. like so [A,C,B], [B,A,C], [B,A,C], [C,A,B] and [C,B,A] i tried using itertools.combinations and I get all combinations just not the ones with all letters in use.

matriks = ["A","B","C"]
    combs=[]
    for i in xrange(1, len(matriks)+1):
    els = [list(x) for x in itertools.combinations(matriks, i)]
    combs.append(els)
print(combs)

this gives the following output

[[['A'], ['B'], ['C']], [['A', 'B'], ['A', 'C'], ['B', 'C']], [['A', 'B', 'C']]]
¿Fue útil?

Solución

You can simply use itertools.permutations:

>>> from itertools import permutations
>>> 
>>> l = ["A","B","C"]
>>> 
>>> list(permutations(l))
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top