假设你有一个像这样的使用计数的默认用户:
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])
答案 0 :(得分:1)
random.shuffle(candidates)
min_candidate = min(candidates, key=usage_counts.get)
返回第一个" minimal"来自候选人名单的候选人。
答案 1 :(得分:0)
如果您接受明确地执行此操作,则可以通过为具有最低计数的候选人生成列表来浏览列表一次。如果当前计数小于旧min,则初始化一个新列表,如果相等则添加到列表中:
def get_least_used(candidates, usage_counts):
mincount = sys.maxint
for c in candidates :
count = usage_counts[c]
if count < mincount:
leastc = [ c ]
mincount = count
elif count == mincount:
leastc.append(c)
return random.choice(leastc)
如您所说,您使用的是Python 2.6,我使用mincount
初始化sys.maxint
。在Python 3.x下,您必须选择合理 的值。