Repeatedly sample and combine elements of a list

Question:

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?

Asked By: ah bon

||

Answers:

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']]
Answered By: S.B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.