【问题标题】:How to get the least used item?如何获得最少使用的物品?
【发布时间】: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

您在某些列表中有候选人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])

【问题讨论】:

  • 随机挑选最少使用的候选人是什么意思?如果你想找到最少使用的候选者,为什么要随机查找?
  • 是的,现在我想起来了,随机选择并不那么重要,因为它会自动调平,但仍然如此。
  • 如果您将数据类型更改为collections.Counter,您可以通过item, count == usage_counts.most_common()[-1]获得最低计数项
  • 该死的 >= 2.7 我被 2.6 困住了
  • 不需要生成器表达式。 lowest = min(candidate_counts.itervalues())

标签: python python-2.6


【解决方案1】:
random.shuffle(candidates)

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

从混杂的候选者列表中返回第一个“最小”候选者。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多