簡體   English   中英

如何解決我目前正在使用的這個問題 random.choices

[英]How can I solve this problem I am currently using random.choices

我有以下代碼:

import random

GENDER = ["F", "M"]
gender_type = random.choice(GENDER)
print(gender_type)

我怎樣才能確保女性和男性性別類型都出現相同的次數,例如

NO_OF_FEMALES =100
NO_OF_MALES = 100

使用random.choice我不能保證 F 和 M 會分別出現 100 次

正如 pjs 指出的那樣,最好的方法是生成一個包含 100 個男性和 100 個女性的列表,然后隨機重新排序。 我認為最好的方法是 Yevhen 指出的方法。 看起來像這樣:

people_per_gender = 100
gender = ["M","F"]
people = 100*gender #at this point the list is ordered: M, F, M, F ...
random.shuffle(people) #now the list people is randomly ordered, use it for whatever you need

#check by printing first 10:
for i in range(10):
     print(people[i])

我將使用較小的集合進行演示。

您將使用隨機性:

import random

構建一個包含每個性別 5 個的列表:

students = ['F'] * 5 + ['M'] * 5    # ['F', 'F', 'F', 'F', 'F', 'M', 'M', 'M', 'M', 'M']
random.shuffle(students)
print(students)  # yields ['M', 'M', 'M', 'F', 'M', 'F', 'F', 'F', 'F', 'M'] for example

現在對students做任何你想做的事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM