Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulating the output of itertools.permutations in python

I want to take a list, for instance List = [1,2,2], and generate its permutations. I can do this with:

NewList = [list(itertools.permutations(List))]

and the output is:

[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]]

The Problem: itertools.permutations returns a list of length 1 whose only entry is the list of all permutations of List. That is:

NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)]

and

NewList[1] does not exist.

I want the output to be a list where each entry is one of the permutations. That is

NewList[0] == (1,2,2)
NewList[1] == (1,2,2)
NewList[2] == (2,1,2)
...
NewList[5] == (2,2,1)

The Question: Is there a command that will produce the permutations of List in this way? Failing that, is there a way to access the 'individual elements' of [list(itertools.permutations(List))] so I can do things with them?

like image 406
The cake is a Lie Avatar asked May 12 '26 22:05

The cake is a Lie


1 Answers

>>> from itertools import permutations
>>> list(permutations([1,2,2]))
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]

You don't need to put it in a list again. i.e Don't do [list(permutations(...))] (By doing [] you are making a nested list and hence are unable to access the elements using testList[index], though you could do testList[0][index] but it would be better to just keep it as a list of tuples.)

>>> newList = list(permutations([1, 2, 2]))
>>> newList[0]
(1, 2, 2)
>>> newList[3]
(2, 2, 1)

Now you can access the elements by using their indices.

like image 128
Sukrit Kalra Avatar answered May 14 '26 13:05

Sukrit Kalra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!