简体   繁体   中英

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?

>>> 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. ie 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.

Why can't you do this:

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

or even just this:

NewList = list(itertools.permutations(List))

By doing [ list(itertools.permutations(List)) ] , you put the list of permutations (the one that you want) inside of another list. So the fix would be to remove the outer [] 's

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