Reputation: 25
Forgive me if this question is a repeat, but I'm stuck with a code I've been working on. I am creating a program for myself to create random teams of people, and I've been trying to find an easy way to make an inserted amount of teams. The area I am suck on is here:
print("How many teams would you like?")
numberteam = input("Number: ")
listnumber = 0
teams = []
while numberteam + 1:
teams.append(Team(str(listnumber + 1)) = [])
I am a fairly new coder, so I'm sure besides the obvious using an expression for a variable there are probably other mistakes, but any suggestions on an easy way to fix this would be great!
Also if I left something out, please just ask! (By the way I am using python)
Upvotes: 0
Views: 72
Reputation: 32459
Maybe you are looking for something like this:
import random
persons = ['Adan', 'Boris', 'Carla', 'Dora', 'Ernesto', 'Floridalma', 'Gustavo', 'Hugo', 'Ines', 'Juan']
random.shuffle (persons)
count = int(input('How many teams? '))
teams = [persons[i::count] for i in range(count)]
for idx, team in enumerate(teams):
print ('Team {}: {}'.format(idx + 1, ', '.join(team)))
The content of person
doesn't need to be strings, it can hold instances of a custom Person
class or whatever you like.
Explanation:
Populate a list from which to chose.
Shuffle it in place.
Prompt the user for the number of teams and convert the input into an integer.
Create the teams. person[i::count]
picks from persons each count-th element starting at index i. Hence if e.g. count is 3, in the first team are the (shuffled) indices 0, 3, 6, etc, in the second team 1, 4, 7, etc, etc.
Print it.
The general slicing notation is iterable[start:stop:step]
.
Or if you want to use dictionaries, you can use a dictionary comprehension:
teams = {'Team{}'.format(i + 1): persons[i::count] for i in range(count)}
for k, v in teams.items():
print ('{}: {}'.format(k, ', '.join(v) ) )
Upvotes: 1
Reputation: 48885
Try this (I cleaned things up a bit):
print("How many teams would you like?")
numberteam = int(input("Number: "))
# Create a dictionary, where each team has an emtpy list
teams = dict([('Team{}'.format(i), []) for i in range(numberteam)])
# The following also works
# teams = {'Team{}'.format(i):[] for i in range(numberteam)}
You can then access the teams like this:
teams['Team3'] # returns an empty list
The longhand for the above is
print("How many teams would you like?")
numberteam = int(input("Number: "))
teams = {}
for i in range(numberteam):
teams['Team{}'.format(i)] = []
Upvotes: 3