【问题标题】:Filter out elements that occur less times than a minimum threshold过滤掉出现次数少于最小阈值的元素
【发布时间】:2017-11-27 19:54:19
【问题描述】:

在尝试使用以下代码计算列表中某个元素的出现次数后

from collections import Counter
A = ['a','a','a','b','c','b','c','b','a']
A = Counter(A)
min_threshold = 3

在上面A上调用Counter后,就形成了这样一个counter对象:

>>> A
Counter({'a': 4, 'b': 3, 'c': 2})

从这里开始,如何使用3 的最小阈值仅过滤'a''b'

【问题讨论】:

    标签: python list-comprehension counter dictionary-comprehension


    【解决方案1】:

    构建您的计数器,然后使用字典理解作为第二个过滤步骤。

    {x: count for x, count in A.items() if count >= min_threshold}
    # {'a': 4, 'b': 3}
    

    【讨论】:

    • 这是次优的,不需要重新查找每个A[x] 来获取该项目的count,只需直接遍历for x, count in A.items()
    【解决方案2】:

    您可以从字典中删除3以下的键:

    for key, cnts in list(A.items()):   # list is important here
        if cnts < min_threshold:
            del A[key]
    

    这给了你:

    >>> A
    Counter({'a': 4, 'b': 3})
    

    【讨论】:

      【解决方案3】:

      正如Satish BV 所涵盖的,您可以使用字典理解来迭代您的计数器。您可以使用 items (或 iteritems 以提高效率,如果您使用的是 Python 2)来获取 (key, value) 元组对的序列。 然后把它变成一个计数器。

      my_dict = {k: v for k, v in A.iteritems() if v >= min_threshold}
      filteredA = Counter(my_dict)
      

      或者,您可以遍历原始 Counter 并删除不必要的值。

      for k, v in A.items():
          if v < min_threshold:
              A.pop(k)
      

      【讨论】:

        【解决方案4】:

        这看起来更好:

        { x: count for x, count in A.items() if count >= min_threshold }
        

        【讨论】:

        • 在 Python 3 中,您需要遍历 for x, count in A.items() 以避免 ValueError: too many values to unpack (expected 2)
        猜你喜欢
        • 2021-11-23
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多