Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to build a Combination String

I have one list, like so,

a = ['dog','cat','mouse']

I want to build a list that is a combination of the all the list elements and looks like,

ans = ['cat-dog', 'cat-mouse','dog-mouse']

This is what I came up with,

a = ['dog','cat','mouse']
ans = []
for l in (a):
    t= [sorted([l,x]) for x in a if x != l]
    ans.extend([x[0]+'-'+x[1] for x in t])
print list(set(sorted(ans)))

Is there a simpler and a more pythonic way!

like image 503
nitin Avatar asked Feb 27 '26 21:02

nitin


2 Answers

How important is the ordering?

>>> a = ['dog','cat','mouse']
>>> from itertools import combinations
>>> ['-'.join(el) for el in combinations(a, 2)]
['dog-cat', 'dog-mouse', 'cat-mouse']

Or, to match your example:

>>> ['-'.join(el) for el in combinations(sorted(a), 2)]
['cat-dog', 'cat-mouse', 'dog-mouse']
like image 86
Jon Clements Avatar answered Mar 02 '26 15:03

Jon Clements


The itertools module:

>>> import itertools
>>> map('-'.join, itertools.combinations(a, 2))
['dog-cat', 'dog-mouse', 'cat-mouse']
like image 40
Josh Lee Avatar answered Mar 02 '26 13:03

Josh Lee