Reputation: 163
My list is:
groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
So I want to print all the unique combinations of teams that will play each other:
Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay
Can I do this with a for loop?
Upvotes: 0
Views: 138
Reputation: 21643
Whenever you're thinking of permutations, combinations, Cartesian products, etc, think of the itertools
library; it's standard to Python. And if it's not in there have a look at sympy.
>>> from itertools import combinations
>>> for c in combinations(groupA, 2):
... '{} Vs. {}'.format(*c)
...
'Russia Vs. Egypt'
'Russia Vs. Saudi Arabia'
'Russia Vs. Uruguay'
'Egypt Vs. Saudi Arabia'
'Egypt Vs. Uruguay'
'Saudi Arabia Vs. Uruguay'
format
is a nice alternative for output too.
Upvotes: 2
Reputation: 6211
This should do what you want:
groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for i in range(len(groupA)):
for j in range(i+1, len(groupA)):
print("{} Vs. {}".format(groupA[i], groupA[j]))
If you prefer using itertools:
from itertools import combinations
groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for combo in combinations(groupA, 2):
print("{} Vs. {}".format(combo[0], combo[1]))
Upvotes: 2
Reputation: 766
This can do the trick:
groupA = ['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for index, country in enumerate(groupA):
for rival in groupA[index+1:]:
print('%s vs %s'%(country, rival) )
Upvotes: 2