在python带权重的列表中随机取值的方法

yipeiwu_com6年前Python基础

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)

以上这篇在python带权重的列表中随机取值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现读写INI配置文件的方法示例

本文实例讲述了Python实现读写INI配置文件的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import ConfigParser im...

python list语法学习(带例子)

创建:list = [5,7,9]取值和改值:list[1] = list[1] * 5列表尾插入:list.append(4)去掉第0个值并返回第0个值的数值:list.pop(0)去...

python使用pipeline批量读写redis的方法

用了很久的redis了。随着业务的要求越来越高。对redis的读写速度要求也越来越高。正好最近有个需求(需要在秒级取值1000+的数据),如果对于传统的单词取值,循环取值,消耗实在是大,...

python覆盖写入,追加写入的实例

追加写入: # -*- coding:utf-8 -*- # a 指定打开文件的模式,a为追加 r为只读 a=open('test.txt', 'a') a.write('追...

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...