3

I have a list of all premier league teams:

teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ]

I need to compute all possible team1-vs-team2 pairings.

At present I have the following code:

oppo = 0

for team in teamlist:
        print team + "-vs-" + teamlist[oppo]
        oppo+=1
        print team + "-vs-" + teamlist[oppo]
        oppo+=1

which will output:

arsenal-vs-arsenal
arsenal-vs-aston-villa

However I need this to go through each team, display all of their possible home game fixtures, then move onto the next team in teamlist, output all of their possible home games fixtures and repeat until all teams are done.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user5740471
  • 51
  • 1
  • 6

3 Answers3

8

An alternative to the nested for loops is to compute all permutations of length 2 from the items of your list.

>>> from itertools import permutations
>>> for team1, team2 in permutations(teamlist, 2):
...     print '{0} -vs- {1}'.format(team1, team2)
... 
arsenal -vs- aston-villa
arsenal -vs- bournemouth
arsenal -vs- chelsea
# and so on ...
timgeb
  • 76,762
  • 20
  • 123
  • 145
3

This can be archieved by looping through the teamlist twice and by checking whether the opponent is "before" the original team. The code does also not depend on external libraries.

teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ]

for team in teamlist:
    for opponent in teamlist:
        if team < opponent:
            print(team + "-vs-" + opponent)
www.data-blogger.com
  • 4,076
  • 7
  • 43
  • 65
1

Doing this recursively in a function should work.

# after defining teamlist

def printVS(start):
    for x in range(1,len(teamlist)-start):
        print teamlist[start],"vs",teamlist[start+x]
    if start < len(teamlist):
        printVS(start+1)

printVS(0)
TiByte
  • 11
  • 3