I'm using itertools
to generate all possible permutations of a list. I would like it to return a list of lists, but this is not what I'm getting.
For example
import itertools
print list(itertools.permutations([1, 2]))
returns
>>> [(1, 2), (2, 1)]
But I was expecting
>>> [[1, 2], [2, 1]]
Is it possible?
The module has a number of functions that construct and return iterators. One such function is the zip_longest function. This function makes an iterator that aggregates elements from each of the iterables. The iteration continues until the longest iterable is not exhausted.
What does itertools. combinations() do ? It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order.
The permutation tuples are emitted in lexicographic order according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value.
Practical Data Science using Python As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator.
Just map your tuples to lists:
import itertools
try:
# Python 2, use Python 3 iterator version of map
from future_builtins import map
except ImportError:
# already using Python 3
pass
map(list, itertools.permutations([1, 2]))
In Python 3, map()
is an iterator too, so the tuples are converted to lists as you iterate.
I'm assuming here that you don't need the full permutations result in one go. You can always call list()
on the map()
, or use a list comprehension instead if you do:
[list(t) for t in itertools.permutations([1, 2])]
or for Python 2, just drop the from future_builtins
import and leave map
to produce a list.
You can use a list comprehension to convert each tuple to a list and collect the results in a list:
>>> [list(p) for p in itertools.permutations([1, 2])]
[[1, 2], [2, 1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With