Two random lists from one list

Tim Chase python.list at tim.thechases.com
Fri Mar 11 13:55:11 EST 2011


On 03/11/2011 12:21 PM, noydb wrote:
> I am just looking to see if there is perhaps a more efficient way of
> doing this below (works -- creates two random teams from a list of
> players).  Just want to see what the experts come up with for means of
> learning how to do things better.
>
> ###
> import random
> players = ["jake", "mike", "matt", "rich", "steve", "tom", "joe",
> "jay"]
> teamA = random.sample(players, 4)
> print teamA
> teamB = []
> for p in players:
>      if p not in teamA:
>          teamB.append(p)
> print teamB

I'd be tempted to do

   temp = players[:] # copy players
   random.shuffle(temp) # you could directly shuffle players
                        # if you don't care about mangling it
   team_a = temp[:4]
   team_b = temp[4:]
   del temp # optional

This assumes you want balanced-ish teams.

-tkc





More information about the Python-list mailing list