[英]Python - choosing random object from a list
我有對象列表“p”,每個對象都有一些數字“a”(例如p [3] .a = 5)。 我想從列表中選擇隨機對象,方式是選擇一個對象的概率與其a值成正比,即選擇a = 5的對象的概率是選擇具有a = 1的對象的概率的五倍。 我怎么能用Python / Pylab / Numpy做到這一點?
謝謝!
這適用於整數計數,但對於大數量計數不會有效。
c = collections.Counter({k:k.a for k in stuff})
random.choice(list(c.elements()))
這是一種更有效的方法。
import random
def weighted_choice(items):
# check if no items exist
if not items:
return None
# compute total of all weights
total = sum(item.weight for item in items)
# select a random point within the total
selection = random.randint(0, total - 1)
# find the corresponding item
count = 0
for item in items:
count += item.weight
if selection < count:
return item
我建議使用bisect
from bisect import bisect
class Element(object):
def __init__(self, value):
self.a = value
def __repr__(self):
return 'Element({})'.format(self.a)
data = [Element(3), Element(5), Element(7), Element(1)]
last = 0
breakpoints = []
for element in data:
breakpoints.append(last + element.a)
last += element.a
print(breakpoints)
for random_value in xrange(last):
pos = bisect(breakpoints, random_value)
print(random_value, data[pos])
您必須使用斷點構建列表一次。 然后,只要您願意,您就可以使用相當快速的bisect算法。
最后一個循環只是為了演示結果。
編輯:獲取斷點的另一種方法(我不喜歡for-loop):
values = [value.a for value in data]
breakpoints = [sum(values[:pos+1]) for pos in xrange(len(values))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.