Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

python - How to select between two values, using one 60% of the times and the other 40% of the time

I'm sorry for the really shitty title but i cant explain it better in a short way.

What im trying to do is to create a generator that generates people. i want the user to be able to specify how many men vs women there should be. Right now i set gender by

gender = random.randint(1, 2)

where 1 = male and 2 = female. lets say i want to create 100 people where 60% of them are women, how do i keep track of it? my code right

    while count != num_of_names:
    l_num = random.randint(0, 149)
    f_num = random.randint(0, 200)
    f_name_male = f_names_males[f_num]
    f_name_female = f_names_females[f_num]
    gender = random.randint(1, 2)
    if gender == 1:
        f_name = f_name_male
    else:
        f_name = f_name_female
    l_name = l_names[l_num]
    names.append((f_name, l_name, gender))
    count += 1
question from:https://stackoverflow.com/questions/65934864/how-to-select-between-two-values-using-one-60-of-the-times-and-the-other-40-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use random.shuffle() and call it to randomise a list. Here is a generator that yields random values 'M' or "F' from a fixed pool in the relative amounts requested:

import random

def gender(n_male, n_female):
    population = list('M' * n_male + 'F' * n_female)
    random.shuffle(population)
    for i in range(len(population)):
        yield population[i]

>>> l = [g for g in gender(40, 60)]
>>> assert l.count('M') == 40
>>> assert l.count('F') == 60
>>> print(f"male : {l.count('M')}, female : {l.count('F')}")
male : 40, female : 60

>>> l = [g for g in gender(50, 50)]
>>> print(f"male : {l.count('M')}, female : {l.count('F')}")
male : 50, female : 50

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...