-1

I have a list of lists say

[[2, 4, 6], [2, 6, 10], [2, 12, 22], [4, 6, 8], [4, 8, 12], [6, 8, 10], [8, 10, 12], [8, 15, 22], [10, 11, 12]]

How do I generate a combination of the lists for a given length?

For example if the given length is 3

Then I need all combinations of 3 list element scenarios from the given list of list.

Example :

[2, 4, 6], [2, 6, 10], [2, 12, 22]

or

[2, 4, 6], [8, 10, 12], [10, 11, 12]
...
... and so forth

and if the given length is 2 then it should be like

[2, 4, 6], [2, 6, 10]

or

[6, 8, 10], [8, 10, 12]
...
... and so forth

I dont want a permutation of elements inside the lists but I want a permutation of the lists itself.

1_0
  • 15
  • 1
  • 7
  • 6
    Have a look at [`itertools.permutations`](https://docs.python.org/2/library/itertools.html#itertools.permutations). – Peter Wood Jun 25 '15 at 15:23
  • possible duplicate of [How to generate all permutations of a list in Python](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – Peter Wood Jun 25 '15 at 15:25
  • 2
    Actually you want [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) specifically `itertools.combinations(L, 3)` if your list was `L` – Cory Kramer Jun 25 '15 at 15:25
  • @PeterWood I dont want a permutation of elements inside the list. But i need the permutation of the lists inside the list itself – 1_0 Jun 25 '15 at 15:28
  • @1_0 The permutations are of the lists in the list. – Peter Wood Jun 25 '15 at 18:02

1 Answers1

1

There are two options here. The first is to use itertools.permutations. This will give you every permutation (i.e: [1,2] and [2,1] would not be the same)

import itertools

lists = [[2, 4, 6], [2, 6, 10], [2, 12, 22], [4, 6, 8], [4, 8, 12], [6, 8, 10], [8, 10, 12], [8, 15, 22], [10, 11, 12]]
n = 3

for perm in itertools.permutations(lists, n):
    print(perm)

If you want completely unique groupings, with no duplicates , use itertools.combinations (i.e: [1,2] and [2,1] would be the same).

for comb in itertools.combinations(lists, n):
    print(comb)
Brobin
  • 3,241
  • 2
  • 19
  • 35