**
choices(population, weights=None, *, cum_weights=None, k=1)
** population:集群。 weights:相对权重。 cum_weights:累加权重。 k:选取次数。
import random
list1 = [1, 2, 3, 4, 5]
choose1 = random.choices(list1, k=5)
choose2 = random.choices(list1, weights=[1, 2, 3, 4, 5], k=5)
choose3 = random.choices(list1, weights=[1, 1, 1, 1, 1], k=5)
choose4 = random.choices(list1, weights=[0, 0, 1, 0, 0], k=5)
print(choose1)
print(choose2)
print(choose3)
print(choose4)
打印结果:
[5, 5, 3, 4, 1]
[4, 3, 5, 3, 2]
[2, 5, 3, 5, 5]
[3, 3, 3, 3, 3]
cum_weights是weights的累加即当weight=[1, 2, 3, 4]时,则cum_weights=[1, 3, 6, 10],小白可以理解为weight=[1, 2, 3, 4]就是cum_weights=[1, 3, 6, 10]
那么当weight=[1, 0, 0, 0]时,cum_weight=[1, 1, 1, 1],所以打印出来的列表只出现选取列表的第一个元素,我们来看如下代码:
import random
list1 = [1, 2, 3, 4, 5, 6]
choose1 = random.choices(list1, weights=[1, 0, 0, 0, 0, 0], k=6)
choose2 = random.choices(list1, cum_weights=[1, 1, 1, 1, 1, 1], k=6)
print(choose1)
print(choose2)
打印结果:
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
|