gpt4 book ai didi

python - 如何从 Python 的 Counter 类中获得加权随机选择?

转载 作者:太空狗 更新时间:2023-10-29 17:43:35 25 4
gpt4 key购买 nike

我有一个程序,我使用 collections.Counter 跟踪各种事情的成功 - 事情的每次成功增加相应的计数器:

import collections
scoreboard = collections.Counter()

if test(thing):
scoreboard[thing]+ = 1

然后,对于 future 的测试,我想偏向于产生最大成功的事物Counter.elements() 似乎很适合这个,因为它返回重复次数等于计数的元素(以任意顺序)。所以我想我可以这样做:

import random
nextthing=random.choice(scoreboard.elements())

但是不,这引发了 TypeError: object of type 'itertools.chain' has no len()。好的,所以 random.choice can't work with iterators .但是,在这种情况下,长度是已知的(或可知的)——它是 sum(scoreboard.values())

我知道遍历未知长度列表并随机选择一个元素的基本算法,但我怀疑还有更优雅的算法。我应该在这里做什么?

最佳答案

您可以使用 itertools.islice 轻松完成此操作获取可迭代对象的第 N 项:

>>> import random
>>> import itertools
>>> import collections
>>> c = collections.Counter({'a': 2, 'b': 1})
>>> i = random.randrange(sum(c.values()))
>>> next(itertools.islice(c.elements(), i, None))
'a'

关于python - 如何从 Python 的 Counter 类中获得加权随机选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9084647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com