I'm looping through a csv.reader() object to access each of the 18 lines (each some info about soccer players) in the original CSV file, and then needing to make up three new teams of 6 from these entries. It's tying my brain in a knot; is there a way to accomplish this using a for loop? Like, how can I loop through one list, then append the first item looped through to team1, the second item looped to team2, and so on? I've gotten as far as using random.choice() from a list of the three lists, but using if and while statements to to keep each list down to 6 entries keeps giving me weird results.
Don't know how much it will help but here is what I have so far:
import csv
import random
team1 = []
team2 = []
team3 = []
teamlists = [team1, team2, team3]
with open('soccer_players.csv') as csv_file:
player_reader = csv.reader(csv_file, delimiter=',')
for line in player_reader:
rando = random.choice(teamlists)
rando.append(line)
# Need to fill up team1, team2, team3 equally.
Here is the CSV file I'm working with:
Name,Height (inches),Soccer Experience,Guardian Name(s)
Joe Smith,42,YES,Jim and Jan Smith
Jill Tanner,36,YES,Clara Tanner
Bill Bon,43,YES,Sara and Jenny Bon
Eva Gordon,45,NO,Wendy and Mike Gordon
Matt Gill,40,NO,Charles and Sylvia Gill
Kimmy Stein,41,NO,Bill and Hillary Stein
Sammy Adams,45,NO,Jeff Adams
Karl Saygan,42,YES,Heather Bledsoe
Suzane Greenberg,44,YES,Henrietta Dumas
Sal Dali,41,NO,Gala Dali
Joe Kavalier,39,NO,Sam and Elaine Kavalier
Ben Finkelstein,44,NO,Aaron and Jill Finkelstein
Diego Soto,41,YES,Robin and Sarika Soto
Chloe Alaska,47,NO,David and Jamie Alaska
Arnold Willis,43,NO,Claire Willis
Phillip Helm,44,YES,Thomas Helm and Eva Jones
Les Clay,42,YES,Wynonna Brown
Herschel Krustofski,45,YES,Hyman and Rachel Krustofski
I wouldn't use a loop to create the teams like you're trying to do.
Instead, if you first read all the players into a list, shuffle that list, then the team lists can be created simply by slicing it up into thirds. This approach would also make it relatively easy to divide the shuffled players list into a different number of teams.
The following illustrates how this could be done:
import csv
import random
with open('soccer_players.csv') as csv_file:
next(csv_file) # skip header row
players = [row[0] for row in csv.reader(csv_file, delimiter=',')]
random.shuffle(players)
team1, team2, team3 = [players[i::3] for i in range(3)]
# display results
for i, team in enumerate([team1, team2, team3], 1):
print('team{}: {}'.format(i, team))
Output:
team1: ['Chloe Alaska', 'Ben Finkelstein', 'Phillip Helm', 'Joe Smith', 'Kimmy Stein', 'Arnold Willis']
team2: ['Matt Gill', 'Jill Tanner', 'Diego Soto', 'Les Clay', 'Herschel Krustofski', 'Bill Bon']
team3: ['Joe Kavalier', 'Karl Saygan', 'Eva Gordon', 'Sammy Adams', 'Sal Dali', 'Suzane Greenberg']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With