Advertisement
Guest User

count.py

a guest
Dec 5th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. from collections import Counter, Iterable
  2.  
  3.  
  4. def count(nested, counted_types=(str, float, int, bytes, bytearray)):
  5.     """
  6.    Функция для подсчета вхождений объектов определенного типа в контейнере
  7.    
  8.    >>> count(['hello', ['world', 'sup'], [2, 'ch', ['python', 'is', 'awesome']]])
  9.    Counter({'hello': 1, 'world': 1, 'sup': 1, 2: 1, 'ch': 1, 'python': 1, 'is': 1, 'awesome': 1})
  10.  
  11.    :param nested: контейнер, в котором необходимо провести подсчет вхождений
  12.    :type nested: Iterable
  13.    :param counted_types: типы данных, которые должны быть учтены при подсчете
  14.    :type: counted_types: Iterable
  15.    :return: Объект, реализующий API словаря, содержащий встреченные значения
  16.    :rtype: Counter
  17.    """
  18.     counter = Counter()
  19.     for item in nested:
  20.         # Iterable - служебный тип, обозначающий итерируемый контейнер
  21.         # Если объект контейнер - рекурсивно считаем данные в нем и обновляем текущий счетчик
  22.         if isinstance(item, Iterable) and item.__class__ not in counted_types:
  23.             counter.update(count(item))
  24.         # Если объект из типов, которые должны быть учтены - добавляем элемент к текущему счетчику
  25.         elif item.__class__ in counted_types:
  26.             counter[item] += 1
  27.         # в проитвном случае - пропускаем элемент
  28.         else:
  29.             pass
  30.     return counter
  31.  
  32.  
  33. # Упрощенный вариант, работающий только с list
  34. def count_simple(nested):
  35.     counter = Counter()
  36.     for item in nested:
  37.         if isinstance(item, list):
  38.             counter.update(count(item))
  39.         else:
  40.             counter[item] += 1
  41.     return counter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement