Suppose we have a list L = ['a', 'b', 'c']
, I would like to perform a group sampling of L
to generate an expected result:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
We can see, in this final output, a list of lists, its each element, there are no repeated elements without considering the order. How to implement it in Python?
Advertisement
Answer
One way of doing it is using combinations
from itertools
module. Do it in a for loop and change its r=
parameter every time. r=1
, r=2
, until r=len(L)
:
from itertools import combinations lst = ["a", "b", "c"] print([list(item) for i in range(1, len(lst) + 1) for item in combinations(lst, i)])
output:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]