如何获得最少使用的物品?

How to get the least used item?

假设您有这样一个使用计数的默认指令:

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

并且您在某个列表中有候选人 foo1foo3foo4foo5

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])

如果您明确同意,您只能浏览一次列表,方法是为计数最低的候选人生成一个列表。如果当前计数小于旧最小值,则初始化一个新列表,如果等于则添加到列表中:

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,我用 sys.maxint 初始化了 mincount。在 Python 3.x 下,您必须选择一个 合理 很好的值。

random.shuffle(candidates)

min_candidate = min(candidates, key=usage_counts.get)

returns 洗牌后的候选人名单中的第一个 "minimal" 候选人。