在python带权重的列表中随机取值的方法
作者:江流静一 时间:2022-05-09 01:44:25
1 random.choice
python random模块的choice方法随机选择某个元素
foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
print choice(foo)
2 random.sample
使用python random模块的sample函数从列表中随机选择一组元素
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回
print slice
print list #原有序列并没有改变。
3 python带权重的随机取值
import random
def random_weight(weight_data):
total = sum(weight_data.values()) # 权重求和
ra = random.uniform(0, total) # 在0与权重和之前获取一个随机数
curr_sum = 0
ret = None
keys = weight_data.iterkeys() # 使用Python2.x中的iterkeys
# keys = weight_data.keys() # 使用Python3.x中的keys
for k in keys:
curr_sum += weight_data[k] # 在遍历中,累加当前权重值
if ra <= curr_sum: # 当随机数<=当前权重和时,返回权重key
ret = k
break
return ret
weight_data = {'a': 10, 'b': 15, 'c': 50}
random_weight(weight_data)
来源:https://blog.csdn.net/u012063773/article/details/79470009
标签:python,列表,随机,取值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Varchar与char的区别
2008-02-28 12:44:00
在生成的静态页面中统计点击次数
2009-11-19 13:20:00
python实现飞机大战
2021-03-05 04:19:26
![](https://img.aspxhome.com/file/2023/8/97388_0s.jpg)
php+html5基于websocket实现聊天室的方法
2023-11-15 06:58:58
python乱序字符串排序的实现方式
2023-08-02 12:14:59
php之redis短线重连案例讲解
2023-06-12 13:16:04
python安装pillow的三种方法
2023-07-20 02:36:53
![](https://img.aspxhome.com/file/2023/5/79495_0s.png)
python mac下安装虚拟环境的图文教程
2021-11-02 23:35:21
![](https://img.aspxhome.com/file/2023/2/82942_0s.jpg)
Python实现简单的学生信息管理系统
2021-06-19 10:59:44
![](https://img.aspxhome.com/file/2023/6/82776_0s.jpg)
用Python编写一个简单的FUSE文件系统的教程
2021-11-21 01:30:36
np.array()函数的使用方法
2022-07-08 08:21:05
Python3 ffmpeg视频转换工具使用方法解析
2021-07-28 15:00:30
![](https://img.aspxhome.com/file/2023/8/99038_0s.png)
IE下,事件触发那点破烂事儿
2009-04-27 12:31:00
Python生成器generator原理及用法解析
2021-10-14 14:00:13
![](https://img.aspxhome.com/file/2023/8/92408_0s.jpg)
SQL Server上进行表设计时表的主键设计问题
2010-06-24 16:10:00
Python3自动安装第三方库,跟pip说再见
2022-03-12 04:34:15
![](https://img.aspxhome.com/file/2023/6/76896_0s.png)
python中的装饰器详解
2022-08-14 04:32:05
Asp Oracle存储过程返回结果集的代码
2011-04-10 11:16:00
TensorFlow实现模型断点训练,checkpoint模型载入方式
2022-01-19 22:32:12
![](https://img.aspxhome.com/file/2023/4/80824_0s.jpg)
python import 上级目录的导入
2021-09-13 00:54:29