Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique combinations of elements from a python list [duplicate]

Edit: This is not a exact duplicate of How to get all possible combinations of a list’s elements?

This topic is about finding unique combinations while the other topic is about finding ALL combinations.

If I have a python list:

 L = [1,2,3,4] 

what's the best way to get all the possible unique combinations of 3 elements from the list like below:

["1,2,3", "1,2,4", "2,3,4", "3,4,1"] 

The order of the elements in the combinations doesn't matter. For example, "1,2,3" and "3,2,1" will be considered the same combination.

I can probably write a few loops to do this but I think there might be a one-liner which can do the same.

like image 520
Allen Avatar asked Aug 13 '13 05:08

Allen


People also ask

How do you get two unique combinations in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you get all possible combinations without repetition in Python?

A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.


1 Answers

You need itertools.combinations:

>>> from itertools import combinations >>> L = [1, 2, 3, 4] >>> [",".join(map(str, comb)) for comb in combinations(L, 3)] ['1,2,3', '1,2,4', '1,3,4', '2,3,4'] 
like image 118
Ashwini Chaudhary Avatar answered Oct 20 '22 10:10

Ashwini Chaudhary