Pregunta

Using Python, I want to randomly select people from a list and put them in groups of 5 without selecting the same person more than once. The people are defined by 2 criteria: age and sex. The list of people looks like this:

PPL= [1, 4, 6], [2, 5, 5], [3, 7, 3], [4, 2, 8], [5, 4, 6]

where the 3 numbers in each list represent: age category (1-5), # of males, # of females. I realize the groupings of 5 don't really matter, as all I have to do is make a random list (and then I could count off 5 at a time), but I'm not sure how to make a random list without reusing people. Any suggestions?
I have started with the following (which really just prints the remaining males and females):

import random

PPL = [1, 4, 6], [2, 5, 5], [3, 7, 3], [4, 2, 8], [5, 4, 6]

age = range(0, 6)
gender = [1, 2]#1 = male, #2 = female

randomAge = random.choice(age)
randomGender = random.choice(gender)

count = 0
PPLcounter = 0
for P in PPL:
        while P[randomGender] > 0:
            PPL[PPLcounter][randomGender] = P[randomGender] - 1
            MRemaining = PPL [PPLcounter][1]
            FRemaining = PPL [PPLcounter][2]
            count = count+1
            print count, MRemaining, FRemaining
        PPLcounter += 1
¿Fue útil?

Solución

Expanding on Joel Cornett's comment and A. Rodas example:

Is this what you want:

import random

def gen_people_in_group(age, num_male, num_female):
    males = ['m%s' % age] * num_male
    females = ['f%s' % age] * num_female
    return males + females

def gen_random_sample(num_in_group=5):
    groups = [1, 4, 6], [2, 5, 5], [3, 7, 3], [4, 2, 8], [5, 4, 6]

    population = []
    for group in groups:
        population += gen_people_in_group(*group)

    random.shuffle(population)

    for idx in xrange(0, len(population), num_in_group):
        yield population[idx:(idx + num_in_group)]

def main():
    for rand_group in gen_random_sample():
        print rand_group

if __name__ == '__main__':
    main()

Here's one output:

['m3', 'f3', 'm5', 'f4', 'm1']
['f4', 'f4', 'm4', 'f2', 'm2']
['m4', 'f3', 'm5', 'm3', 'f5']
['m3', 'f5', 'f1', 'm3', 'f4']
['m5', 'f2', 'f1', 'f1', 'f5']
['m1', 'f2', 'f2', 'f1', 'm2']
['f5', 'f4', 'f4', 'm2', 'f4']
['m3', 'm2', 'f2', 'f1', 'f5']
['m3', 'm5', 'm2', 'f5', 'f1']
['m1', 'm3', 'f3', 'm1', 'f4']
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top