我有一个程序,我正在使用跟踪各种事情的成功collections.Counter
-每件事的成功都会增加相应的计数器:
import collections
scoreboard = collections.Counter()
if test(thing):
scoreboard[thing]+ = 1
然后,对于未来的测试,我想偏向那些产生最大成功的东西。Counter.elements()
对此似乎很理想,因为它返回重复次数等于计数的元素(以任意顺序)。所以我想我可以这样做:
import random
nextthing=random.choice(scoreboard.elements())
但是不,这会引发TypeError: object of type 'itertools.chain' has no len()。好的,所以random.choice
不能使用 iterators。但是,在这种情况下,长度是已知的(或可知的)——它是sum(scoreboard.values())
.
我知道遍历未知长度列表并随机选择一个元素的基本算法,但我怀疑还有更优雅的东西。我应该在这里做什么?