Skip to content Skip to sidebar Skip to footer

Selecting Random Values From List Until They Are Gone In Python

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

Solution 1:

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

Is this what you want:

import random

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

defgen_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)]

defmain():
    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']

Post a Comment for "Selecting Random Values From List Until They Are Gone In Python"