我需要一个数据结构来保留元素数,然后在一定范围内检索元素。
示例:
counter = RangeCounter()
for el in [1, 1, 2, 2, 2, 0]
counter.add(el)
counter.get(occurence >= 1 and occurence <= 2)
>>> 1, 2 (element 1 is encountered 2 times)
>>> 2, 3 (element 2 in encountered 3 times)
答案 0 :(得分:3)
使用collections.Counter
,您可以执行所有操作:
from collections import Counter
counter = Counter([1, 1, 2, 2, 2, 0])
# Counter({2: 3, 1: 2, 0: 1})
# occurence >= 1 and occurence <= 2
res = {item: count for item, count in counter.items() if 1 <= count <= 2}
# {1: 2, 0: 1}