Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Soccer League: Need help sorting experienced players evenly among teams

I put this question to Stack Exchange and got some well-intentioned but comically complicated and over-my-head answers. I have basically figured out what I need to do to finish this project EXCEPT for the actual breaking down of experienced and then inexperienced players evenly among the lists. But I can't figure out how to use a for loop to loop through some data and append the first thing to list a, the second thing to list b, the third thing to list c, etc. Anyone know how to do this?

For example:

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.

1 Answer

i don't know what your data look like but one way you could do this is with modulo. if your data entries are sequentially numbered, then you could take the mod 3 of each line number and assign to your lists accordingly. the result of any number mod 3 can only be 0, 1 or 2, one for each list you have. assign the 0s to list 1, 1s to list 2, 2s to list 3 for example.

Thanks for this and all the help I see you giving around here, james. Your answer provided some clarity to one of the less mind-twisting Stack Overflow answers and I ended up filling the empty team lists with list slices based on total list length from two separate shuffled lists of experienced/inexperienced players. I'm sure there's a better way to divide up as perfectly evenly by height as possible but...yeah. Haha. Thanks again.