从列表中选择随机值,直到它们在Python中消失

时间:2013-04-07 02:39:34

标签: python arrays list random population

使用Python,我想从列表中随机选择人物并将其放在5个一组中,而不是多次选择同一个人。人们由2个标准定义:年龄和性别。人员列表如下所示:

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

其中每个列表中的3个数字代表:年龄类别(1-5),男性数量,女性数量。 我意识到5的分组并不重要,因为我所要做的就是制作一个随机列表(然后我可以一次计算5个),但我不确定如何在不重复使用的情况下制作随机列表人。有什么建议吗? 我从以下开始(实际上只打印剩下的男性和女性):

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

1 个答案:

答案 0 :(得分:0)

扩展Joel Cornett的评论和A. Rodas的例子:

这就是你想要的:

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()

这是一个输出:

['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']