假设你有一个使用计数的默认dict,如下所示:
usage_counts = collections.defaultdict(int)
usage_counts['foo1'] = 3
usage_counts['foo2'] = 3
usage_counts['foo3'] = 1
usage_counts['foo4'] = 1
usage_counts['foo5'] = 56
usage_counts['foo6'] = 65
在一些列表中有候选者foo1
、foo3
、foo4
和foo5
:
candidates = ['foo1', 'foo3', 'foo4', 'foo5']
如何从最少使用的候选人中随机挑选
我想出了这个函数,但我想知道是否有更好的方法
def get_least_used(candidates, usage_counts):
candidate_counts = collections.defaultdict(int)
for candidate in candidates:
candidate_counts[candidate] = usage_counts[candidate]
lowest = min(v for v in candidate_counts.values())
return random.choice([c for c in candidates if candidate_counts[c] == lowest])
如果您接受显式地浏览列表,则只能浏览一次,方法是为具有最低计数的canditate生成一个列表。如果当前计数小于旧最小值,则初始化新列表,如果等于,则添加到列表:
正如您所说的使用python2.6,我用
sys.maxint
初始化mincount
。在python3.x下,您必须选择一个合理的值great返回洗牌候选列表中的第一个“最小”候选
相关问题 更多 >
编程相关推荐