Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want itertools to return a list of lists

Tags:

python

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?

like image 762
francoiskroll Avatar asked Mar 06 '17 12:03

francoiskroll


People also ask

What does Itertools Zip_longest return?

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 combination return?

What does itertools. combinations() do ? It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order.

How does Itertools permutations work?

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.

How do you create a Cartesian product of two lists in Python?

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.


2 Answers

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.

like image 69
Martijn Pieters Avatar answered Oct 09 '22 15:10

Martijn Pieters


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]]
like image 7
mkrieger1 Avatar answered Oct 09 '22 16:10

mkrieger1