我需要将人员分成团队,每个团队对这些团队都有一定数量的男性和女性,我编写了以下代码,但我不知道如何修改它,以便生成的团队具有正确的数量其中的男性和女性。
代码是:
from random import randint
def generateTeams(peopleList, numberOfTeams):
""" Given a list of of people and a number of teams (int) to split them into,
" returns a list of randomly allocated teams. If the people do not divide
" evenly into teams then the optimum solution will be chosen.
"""
#Calculate optimum team size
idealTeamSize = len(peopleList) / numberOfTeams
#Empty lists
teams = []
teamsReturn = []
#Generate empty teams
for i in range(0, numberOfTeams):
teams.append([]);
#While we still have people
while(len(peopleList) > 0):
randomIndex = randint(0, len(peopleList)-1)
#Or until there are no teams left in the initial list
if (len(teams) == 0):
print len(peopleList)
break
#Add a random person to the first team in the list
teams[0].append(peopleList[randomIndex])
#And remove them from the peopleList
peopleList.pop(randomIndex)
#If a team has reached optimal size, remove it
if (len(teams[0]) >= idealTeamSize):
teamsReturn.append(teams.pop(0))
#Randomly allocate remainder
while(len(peopleList) > 0):
randomIndex = randint(0, len(teamsReturn)-1)
teamsReturn[randomIndex].append(peopleList.pop(0));
return teamsReturn
# Open the file
f = open('teamselection.csv', 'r')
# Extract the team names and stats
TeamNames = f.readline()[:-1].split(',')[1:]
Men = [int(s) for s in f.readline()[:-1].split(',')[1:]]
Women = [int(s) for s in f.readline()[:-1].split(',')[1:]]
MinDriver = [int(s) for s in f.readline()[:-1].split(',')[1:]]
PrefDriver = [int(s) for s in f.readline()[:-1].split(',')[1:]]
MinMusic = [int(s) for s in f.readline()[:-1].split(',')[1:]]
PrefMusic = [int(s) for s in f.readline()[:-1].split(',')[1:]]
MinMaleLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
PrefMaleLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
MinFemLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
PrefFemLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
MinLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
PrefLead = [int(s) for s in f.readline()[:-1].split(',')[1:]]
Importance = [int(s) for s in f.readline()[:-1].split(',')[1:]]
# Skip the data header line
f.readline()
# Read and save the rest of the lines
Lines = f.readlines()
f.close()
# Set up a range T to iterate over
T = range(len(TeamNames))
# Store record for the volunteers. Each is in a list with the following information
# 0: Name
# 1: Gender M/F
# 2: Music score
# 3: Leadership score
# 4: Driver (1 is a driver)
# 5: List of team indicators - 1 is a mandatory team, -1 is an excluded team
People = []
for line in Lines:
fields = line[:-1].split(',')
People.append([fields[0], fields[1], int(fields[2]), int(fields[3]), int (fields[4]),
[int(fields[5+t]) for t in T]])
P = range(len(People))
#Get actual names into this list
peopleNames = []
#Grab the names
for i in People:
peopleNames.append(i[0] + " " + i[1])
#Find teams using names
print generateTeams(peopleNames, 9)