Two random lists from one list

N

noydb

Hello All,

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.

Thanks for any responses!

###
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
 
C

Chris Hulan

Hello All,

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.

Thanks for any responses!

###
import random
players =
teamA = random.sample(players, 4)
print teamA
teamB = []
for p in players:
    if p not in teamA:
        teamB.append(p)
print teamB

How about:

players = ["jake", "mike", "matt", "rich", "steve", "tom", "joe",
"jay"]
random.shuffle(players)
teamA, TeamB = players[:4],players[4:]
 
P

Peter Otten

noydb said:
Hello All,

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.

Thanks for any responses!

###
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

How about
random.shuffle(players)
teamA = players[:4]
teamB = players[4:]
teamA, teamB
(['tom', 'mike', 'jay', 'rich'], ['jake', 'matt', 'joe', 'steve'])
 
T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top