python - 如何获得最少使用的元素?

标签 python python-2.6

假设您有一个默认的使用计数字典,如下所示:

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

最佳答案

random.shuffle(candidates)

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

返回重新排列的候选列表中的第一个“最小”候选。

关于python - 如何获得最少使用的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197760/

相关文章:

python - xlrd 将字符串读取为 float

python - 在 Python3.6+ 中从集合中弹出随机元素的最 Pythonic 方式是什么?

python - Keras 有没有办法立即停止训练?

python - 无效的语法错误python 2.6

python - Python多播接收器中的重复数据包

python - 列表中每个元素与每个其他元素的总和

python - 如何使用 python pyodbc 模块更新 MSSQL 中的日期时间字段

Python不逐行写入

python - 即使文件存在也没有文件错误