1

Say I have a list of lists: beers.

speights = [1, 10]    
tui = [2, 7]    
export = [3, 9]    
beers = [speights, tui, export]

So I can only find how to get every possible combination of a list of lists which would be: (itertools.product(*beers)) but this gives me every combination including the ratings and the index of each beer aswell.

To make this more clear because I am struggling to explain this concept:

[[speights], [speights, tui], [speights, export], [speights, tui, export], 
 [tui], [tui, speights], [tui, export], [tui, speights, export]
 ..... etc.]

This is the desired output and it has to work on a list of lists of any length.

Any help would be greatly appreciated and sorry if it's been asked before because I can't seem to find this specific problem.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Blue Eden
  • 59
  • 6

2 Answers2

1

You are looking for permutations of any length. Try this:

import itertools
...
c = []
for i in range(len(beers)):
    c.extend(itertools.permutations(beers, i + 1))
print(c)

will yield

[([1, 10],), ([2, 7],), ([3, 9],), ([1, 10], [2, 7]), ([1, 10], [3, 9]),
 ([2, 7], [1, 10]), ([2, 7], [3, 9]), ([3, 9], [1, 10]), ([3, 9], [2, 7]), 
 ([1, 10], [2, 7], [3, 9]), ([1, 10], [3, 9], [2, 7]), ([2, 7], [1, 10], [3, 9]), 
 ([2, 7], [3, 9], [1, 10]), ([3, 9], [1, 10], [2, 7]), ([3, 9], [2, 7], [1, 10])]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

You could combine permutations with chain.from_iterable:

>>> from itertools import permutations, chain
>>> beers = ['speights', 'tui', 'export']
>>> list(chain.from_iterable(permutations(beers, i) for i in xrange(1, len(beers) + 1)))
[('speights',), ('tui',), ('export',), ('speights', 'tui'), ('speights', 'export'), ('tui', 'speights'), ('tui', 'export'), ('export', 'speights'), ('export', 'tui'), ('speights', 'tui', 'export'), ('speights', 'export', 'tui'), ('tui', 'speights', 'export'), ('tui', 'export', 'speights'), ('export', 'speights', 'tui'), ('export', 'tui', 'speights')]
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Thanks, this works perfectly! Just wondering is there any way to get it to be able to have multiple of it's self? so one listoflists could be (tui, tui, speights), (tui, tui, tui) etc? – Blue Eden May 17 '16 at 06:17
  • @BlueEden: You could do that by calling `product(beers, repeat=i)` instead of `permutations(beers, i)`, see [other question](http://stackoverflow.com/questions/3099987/generating-permutations-with-repetitions-in-python) for details. – niemmi May 17 '16 at 06:26