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!
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']
The itertools module:
>>> import itertools
>>> map('-'.join, itertools.combinations(a, 2))
['dog-cat', 'dog-mouse', 'cat-mouse']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With