1
votes

hello i need to know how can i get all the unique possible combinations of a list in such an interesting way:

eg:

myLIST=[70,90,100]

i want to make either two or a single digit unique combination.. i.e;

final_list=[ { [100 , 70] , [90] } , { [100 , 90] , [70] }]

here in this example: there possible only these two sublists;

as; if i take [{ [70,100] , [90] }] or [{[90,100],[70]}] the sublists combinations starts repeating

Note : for a list of 5 elements;i just need those combination lists which have either 3 elemnts or two elements

eg:myLIST=[10,20,30,40,50]

final_list=[{[10,30,50],[20,40]}] , {[10,50],[20,50,30]} and so on..

here i have taken only the sublists of size 2 or 3

1

1 Answers

0
votes

You can use itertools (a built-in python library) to generate combinations of lists:

from itertools import combinations

sample_list = ['a', 'b', 'c', 'c']
list_combinations = list()
sample_set = set(sample_list)

for n in range(len(sample_set) + 1):
    list_combinations += list(combinations(sample_set, n))

print(list_combinations)

returns:

[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

You can find more information about itertools here: https://datagy.io/python-combinations-of-a-list/