假设您有一个默认的使用计数字典,如下所示:
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])
最佳答案
random.shuffle(candidates)
min_candidate = min(candidates, key=usage_counts.get)
返回重新排列的候选列表中的第一个“最小”候选。
关于python - 如何获得最少使用的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197760/