过滤掉出现次数少于最小阈值的元素

Filter out elements that occur less times than a minimum threshold

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

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

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

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

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

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

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

您可以从字典中删除 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})

Satish BV 所述,您可以使用字典理解遍历 Counter。您可以使用项目(或 iteritems 以提高效率,如果您使用 Python 2)来获取一系列(键,值)元组对。 然后把它变成一个计数器。

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)

这个看起来更好看:

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