在计数器中删除计数小于阈值的对象。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在计数器中删除计数小于阈值的对象。相关的知识,希望对你有一定的参考价值。
我有一个声明为:main_dict = Counter()
的计数器,并将值添加为main_dict[word] += 1
。最后,我想删除频率小于15的所有元素。在Counters
有任何功能来做到这一点。
任何帮助赞赏。
答案
不,您需要手动删除它们。使用itertools.dropwhile()
可能会更容易:
from itertools import dropwhile
for key, count in dropwhile(lambda key_count: key_count[1] >= 15, main_dict.most_common()):
del main_dict[key]
示范:
>>> main_dict
Counter('baz': 20, 'bar': 15, 'foo': 10)
>>> for key, count in dropwhile(lambda key_count: key_count[1] >= 15, main_dict.most_common()):
... del main_dict[key]
...
>>> main_dict
Counter('baz': 20, 'bar': 15)
通过使用dropwhile
,您只需要测试计数为15或以上的密钥;之后它会放弃测试,只是通过一切。这对排序的most_common()
列表非常有用。如果有大量值低于15,则可以节省所有这些测试的执行时间。
另一答案
>>> main_dict = Counter('apple': 20, 'orange': 14, 'mango': 26, 'banana': 12)
>>> for k in main_dict:
if main_dict[k] < 15:
del main_dict[k]
>>> main_dict
Counter('mango': 26, 'apple': 20)
另一答案
另一种方法:
c = Counter('baz': 20, 'bar': 15, 'foo': 10)
print Counter(el for el in c.elements() if c[el] >= 15)
# Counter('baz': 20, 'bar': 15)
另一答案
我可以建议另一个解决方案
from collections import Counter
main_dict = Counter('baz': 20, 'bar': 15, 'foo': 10)
trsh = 15
main_dict = Counter(dict(filter(lambda x: x[1] >= trsh, main_dict.items())))
print(main_dict)
>>> Counter('baz': 20, 'bar': 15)
我也有同样的问题,但我需要从Counter返回一个列表,其值大于某个阈值。去做这个
keys_list = map(lambda x: x[0], filter(lambda x: x[1] >= trsh, main_dict.items()))
print(keys_list)
>>> ['baz', 'bar']
另一答案
阈值为零时的优雅解决方案:
main_dict += Counter()
另一答案
如何过滤计数器中计数大于或小于阈值的项目的示例
from collections import Counter
from itertools import takewhile, dropwhile
data = (
"Here's a little song about Roy G. Biv. "
"He makes up all the colors that you see where you live. "
"If you know all the colors, sing them with me: "
"red, orange, yellow, green, blue, indigo, violet all that you see."
)
c = Counter(data)
more_than_10 = dict(takewhile(lambda i: i[1] > 10, c.most_common()))
less_than_2 = dict(dropwhile(lambda i: i[1] >= 2, c.most_common()))
print(f"> 10 more_than_10 \n2 < less_than_2")
输出:
> 10 ' ': 40, 'e': 23, 'o': 16, 'l': 15, 't': 12
2 < "'": 1, 'R': 1, 'G': 1, 'B': 1, 'p': 1, 'I': 1, 'f': 1, ':': 1
以上是关于在计数器中删除计数小于阈值的对象。的主要内容,如果未能解决你的问题,请参考以下文章