从列表中选择随机值,直到它们在Python中消失 [英] Selecting random values from list until they are gone in Python
问题描述
我想使用Python从列表中随机选择一个人,然后将他们分成5人一组,而不要一次选择同一个人.人群由2个标准定义:年龄和性别.人员列表如下所示:
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]
PPL= [1, 4, 6], [2, 5, 5], [3, 7, 3], [4, 2, 8], [5, 4, 6]
其中每个列表中的3个数字代表:年龄类别(1-5),男性数量,女性数量.我意识到将5个分组确实无关紧要,因为我要做的只是创建一个随机列表(然后我可以一次算出5个),但是我不确定如何在不重复使用的情况下创建随机列表人们.有什么建议吗?
我从以下内容开始(实际上只是打印其余的男性和女性):
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
推荐答案
扩展Joel Cornett的评论和A. Rodas的示例:
Expanding on Joel Cornett's comment and A. Rodas example:
这是您想要的吗?
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']
这篇关于从列表中选择随机值,直到它们在Python中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!