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

2024-05-16 06:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你有一个使用计数的默认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

在一些列表中有候选者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])

Tags: inforusagecandidatecollectionsint计数candidates
2条回答

如果您接受显式地浏览列表,则只能浏览一次,方法是为具有最低计数的canditate生成一个列表。如果当前计数小于旧最小值,则初始化新列表,如果等于,则添加到列表:

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)

正如您所说的使用python2.6,我用sys.maxint初始化mincount。在python3.x下,您必须选择一个合理的值great

random.shuffle(candidates)

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

返回洗牌候选列表中的第一个“最小”候选

相关问题 更多 >