0

I've got two lists

All_Teams = [a,b,c,d,e...] #has 30 items

Players = [p1, p2, p3, p4, p5, p6] #has 6 items currently, but this will be varied

In this example I want to assign x number of random teams to each player, where x = All_Teams/Players (5 in this example). But once a team has be assigned to a player it can't be assigned to another player.

I've managed to work it out in a long winded way, by doing the following:

Player1_List = All_Teams

Player1_Teams = random.sample (Player1_List, 5)

Player2_List = [team for team in All_Teams if team not in Player1_Teams]

Player2_Teams = random.sample (Player2_List, 5)

and repeat this process for the 6 players.

print (Player#_Teams)

But I want to simplify it so it loops through for a changing number of players.

I've started with

def assigning_teams():

for player in Players:

    print (player)

But then I'm stuck, as I know I can't change a list I'm iterating through.

Thanks in advance, a python newbie.

1 Answers1

0

Shuffle the All_Teams list, split in it into x parts and there you have it, groups for each player:

import random

All_Teams = [i for i in range(30)]
Players = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'] 

assert len(All_Teams) % len(Players) == 0
x = int(len(All_Teams) / len(Players))

random.shuffle(All_Teams)
players_teams = {Players[i]:All_Teams[i*x:(i+1)*x] for i in range(x)}

which yields e.g.:

{'p1': [2, 16, 10, 9, 17],
 'p2': [6, 1, 19, 0, 8],
 'p3': [21, 29, 24, 15, 4],
 'p4': [26, 14, 28, 11, 20],
 'p5': [23, 5, 12, 22, 13]}
alex
  • 10,900
  • 15
  • 70
  • 100