作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个程序,我使用 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/
我是一名优秀的程序员,十分优秀!