欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-16 13:26:22
1 random.choice python random模块的choice方法随机选择某个元素 foo = ['a', 'b', 'c', 'd', 'e']...

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带权重的列表中随机取值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。