【发布时间】:2015-01-28 16:47:10
【问题描述】:
假设你有一个这样的使用计数的默认字典:
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])
【问题讨论】:
-
随机挑选最少使用的候选人是什么意思?如果你想找到最少使用的候选者,为什么要随机查找?
-
是的,现在我想起来了,随机选择并不那么重要,因为它会自动调平,但仍然如此。
-
如果您将数据类型更改为
collections.Counter,您可以通过item, count == usage_counts.most_common()[-1]获得最低计数项 -
该死的 >= 2.7 我被 2.6 困住了
-
不需要生成器表达式。
lowest = min(candidate_counts.itervalues())
标签: python python-2.6