**
choices(population, weights=None, *, cum_weights=None, k=1)
**
population:集群。
weights:相对权重。
cum_weights:累加权重。
k:选取次数。
复制代码
1
2
3
4
5
6
7
8
9
10
11import random list1 = [1, 2, 3, 4, 5] choose1 = random.choices(list1, k=5) #list1中各个元素出现次数基本持平 choose2 = random.choices(list1, weights=[1, 2, 3, 4, 5], k=5) #list1中第一个元素出现的概率为1/(1+2+3+4+5) choose3 = random.choices(list1, weights=[1, 1, 1, 1, 1], k=5) #list1中每个元素出现的概率相同 choose4 = random.choices(list1, weights=[0, 0, 1, 0, 0], k=5) #每次打印出来都是list1中第三个元素 print(choose1) print(choose2) print(choose3) print(choose4)
打印结果:
复制代码
1
2
3
4
5[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],所以打印出来的列表只出现选取列表的第一个元素,我们来看如下代码:
复制代码
1
2
3
4
5
6
7import 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
2
3[1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1]
最后
以上就是机灵电源最近收集整理的关于Python学习:choices()的相对权重与累加权重理解的全部内容,更多相关Python学习:choices()内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复