def counter_random(counter, filter=None):
"""Return a single random elements from the Counter collection, weighted by count."""
if filter is not None:
counter = { k : v for k,v in counter.items() if filter(k) }
if len(counter) == 0:
raise Exception("No matching elements in Counter collection")
seq = list(counter.keys())
cum = list(itertools.accumulate(list(counter.values()), op.add))
return seq[bisect.bisect_left(cum, random.uniform(0, cum[-1]))]
评论列表
文章目录