Reputation: 19339
With four letters in a list
letters = ['a', 'b', 'c', 'd']
I would like to create another list with every letter in a combination so the result would look like:
['a-b', 'a-c', 'a-d'
'b-a', 'b-c', 'b-d',
'c-a', 'c-b', 'c-d',
'd-a', 'd-b', 'd-c']
How can it be done?
Upvotes: 0
Views: 313
Reputation: 1480
As others have noted, there's a standard library function to generate all given-length permutations from a list:
import itertools
combo = [ '-'.join(pair) for pair in itertools.permutations(letters,2) ]
For pairs from short lists, the basic list comprehension option is not too bad (but still second-best):
combo = [ f+'-'+s for fx,f in enumerate(letters) for sx, s in enumerate(letters) if fx!=sx ]
Upvotes: 2
Reputation: 1055
Look into permutations
:
import itertools
permutations = list(itertools.permutations(['a', 'b', 'c', 'd'], 2))
permutations = [elem[0]+"-"+elem[1] for elem in permutations]
This achieves the same as the following, which you may be more familiar with :
permutations = []
for letter_1 in letters:
for letter_2 in letters:
if letter_1 != letter_2:
permutations.append(letter_1 + "-" + letter_2)
Upvotes: 2
Reputation: 1994
The you're looking to make all combinations of the elements of an array as suggested by @quamrana this can be done via itertools.permutation
This function takes the list and the length of the permutation as an input and returns a iterator.
So you need to call
perms = itertools.permutations(['a', 'b', 'c', 'd'], 2)
to get the iterator
Now you can iterate over it and add dashes in the middle via
result = [i[0]+"-"+i[1] for i in perms]
Upvotes: 2
Reputation: 4690
You're probably looking to use the itertools.permutations()
function:
>>> import itertools
>>> res = [f"{i[0]}-{i[1]}" for i in itertools.permutations(letters, 2)]
>>> res
['a-b', 'a-c', 'a-d', 'b-a', 'b-c', 'b-d', 'c-a', 'c-b', 'c-d', 'd-a', 'd-b', 'd-c']
Upvotes: 1
Reputation: 4142
The itertools.permutations
function does exactly that
from itertools import permutations
letters = ["a", "b", "c", "d"]
print(["-".join(perm) for perm in permutations(letters, 2)])
If you don't care about ordering (so a-b
would be the same as b-a
) then use itertools.combinations
Upvotes: 6