本文整理汇总了Python中collections.Counter.subtract方法的典型用法代码示例。如果您正苦于以下问题:Python Counter.subtract方法的具体用法?Python Counter.subtract怎么用?Python Counter.subtract使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.Counter
的用法示例。
在下文中一共展示了Counter.subtract方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _HitLog
# 需要导入模块: from collections import Counter [as 别名]
# 或者: from collections.Counter import subtract [as 别名]
class _HitLog(AbstractLog):
# This is a storage class that keep track of the hits that have
# occurred over a given duration.
# This particular implementation keeps track of hits in-memory.
def __init__(self, duration, _): # last argument is resource (or None), but it is unused.
self._hits = []
self._delta = duration if isinstance(duration, timedelta) \
else timedelta(seconds=duration)
self._thread_lock = Lock()
self._counter = PyCounter()
def _prune(self):
if self._delta.total_seconds() < 0:
# negative seconds means keep everything.
return
now = datetime.now()
with self._thread_lock:
while self._hits and (now - self._hits[0][0]) > self._delta:
time, pickled_counter_keys = heapq.heappop(self._hits)
self._counter.subtract(pickle.loads(pickled_counter_keys))
def _generate_counter_keys(self, partitions):
sub_keys = chain.from_iterable(
combinations(partitions, r) for r in range(1, len(partitions)+1)
)
for key_list in sub_keys:
counter_key = tuple(sorted(map(lambda k: (k, partitions[k]), key_list)))
yield counter_key
def track(self, partitions):
now = datetime.now()
with self._thread_lock:
counter_keys = tuple(self._generate_counter_keys(partitions))
heapq.heappush(self._hits, (now, pickle.dumps(counter_keys)))
self._counter.update(counter_keys)
def count(self, **partitions):
self._prune()
if not partitions:
return len(self._hits)
else:
counter_key = tuple(sorted(partitions.items()))
return self._counter[counter_key]
def __add__(self, other):
if isinstance(other, _HitLog):
if self._delta != other._delta:
return NotImplemented
else:
new_log = _HitLog(self._delta, None)
new_log._hits.extend(self._hits)
new_log._hits.extend(other._hits)
heapq.heapify(new_log._hits)
new_log._counter.update(self._counter)
new_log._counter.update(other._counter)
return new_log
else:
return NotImplemented
def __iter__(self):
ascending = heapq.nsmallest(self.count(), self._hits)
for time, partitions in ascending:
yield Hit(time, partitions)
def __len__(self):
return self.count()
def __repr__(self):
return "HitLog({})".format(self.count())
示例2: subtract
# 需要导入模块: from collections import Counter [as 别名]
# 或者: from collections.Counter import subtract [as 别名]
def subtract(self, *args, **kwargs):
Counter.subtract(self, *args, **kwargs)
self.clean()