Reputation: 359
I have a set of variables in a list
list = [ 'A', 'B', 'C']
I iteratively remove one variable from the list and append this to the original list in a list of lists, stopping when the list only has one item. For example, the output using the list above would be:
list_of_var_lists = [
[['A', 'B', 'C'], ['A', 'B'], ['A']],
[['A', 'B', 'C'], ['A', 'B'], ['B']],
[['A', 'B', 'C'], ['A', 'C'], ['A']],
[['A', 'B', 'C'], ['A', 'C'], ['C']],
[['A', 'B', 'C'], ['B', 'C'], ['B']],
[['A', 'B', 'C'], ['B', 'C'], ['C']]
]
How would i do for a list of any size?
Many thanks, J
Upvotes: 2
Views: 71
Reputation: 52008
Here is a solution using itertools.permutations. It is a generator rather than a massive lists of lists of lists, since the number of such sublists grows hyper-exponentially:
import itertools
def list_unpacker(ls):
for p in itertools.permutations(ls):
sublists = []
current_list = ls[:]
sublists.append(current_list)
for x in p[:-1]:
current_list = [y for y in current_list if y != x]
sublists.append(current_list)
yield sublists
for lists in list_unpacker(['a','b','c']):
print(lists)
Output:
[['a', 'b', 'c'], ['b', 'c'], ['c']]
[['a', 'b', 'c'], ['b', 'c'], ['b']]
[['a', 'b', 'c'], ['a', 'c'], ['c']]
[['a', 'b', 'c'], ['a', 'c'], ['a']]
[['a', 'b', 'c'], ['a', 'b'], ['b']]
[['a', 'b', 'c'], ['a', 'b'], ['a']]
Upvotes: 4