Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out elements that occur less times than a minimum threshold

After trying to count the occurrences of an element in a list using the below code

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

After calling Counter on A above, a counter object like this is formed:

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

From here, how do I filter only 'a' and 'b' using minimum threshold value of 3?

like image 607
Satish Bandaru Avatar asked Jun 24 '17 09:06

Satish Bandaru


1 Answers

Build your Counter, then use a dict comprehension as a second, filtering step.

{x: count for x, count in A.items() if count >= min_threshold}
# {'a': 4, 'b': 3}
like image 94
cs95 Avatar answered Oct 19 '22 17:10

cs95