Home > database >  How to assign list of teams to a list of users randomly in python
How to assign list of teams to a list of users randomly in python

Time:11-23

For example:

Team User
USA Mark
England Sean
India Sri

assigning users to different teams randomly

CodePudding user response:

You could use shuffle to shuffle a user list;

from random import shuffle
teams = ['USA', 'England', 'India']
users = ['Mark', 'Sean', 'Sri']
shuffle(users)
print([(t,u) for t,u in zip(teams, users)])

To assign multiple teams to a player, you can use iter() to ensure there are no duplicates

from random import shuffle
teams = ['USA', 'England', 'India','France', 'Brazil', 'Australia']
users = ['Mark', 'Sean', 'Sri']
shuffle(teams)
teams_iter = iter(teams)
print([(u,(t1,t2)) for u,t1,t2 in zip(users, teams_iter, teams_iter )])

CodePudding user response:

In random module use choice

from random import choice
choice(['USA','England','India'])
'India'

For a dataframe of users you could use lambda to get a random choice for each user:

df.apply (lambda x: choice(['USA','England','India']))

CodePudding user response:

Here a posible solution

from random import randrange

User = ['Mark', 'Sean', 'Sri']
Team = ['USA', 'England', 'India']
_range = len(User)

new_list  = []

while len(new_list) != _range:
  try:
    rr = randrange( len(Team) );
    new_list.append( [Team.pop(), User.pop( rr ) ] )
  except:
    ""

print(new_list)

  • Related