Reputation: 59
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.
Upvotes: 1
Views: 70
Reputation: 17263
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')]
Upvotes: 1
Reputation: 59164
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])]
Upvotes: 1