Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import Counter, Iterable
- def count(nested, counted_types=(str, float, int, bytes, bytearray)):
- """
- Функция для подсчета вхождений объектов определенного типа в контейнере
- >>> count(['hello', ['world', 'sup'], [2, 'ch', ['python', 'is', 'awesome']]])
- Counter({'hello': 1, 'world': 1, 'sup': 1, 2: 1, 'ch': 1, 'python': 1, 'is': 1, 'awesome': 1})
- :param nested: контейнер, в котором необходимо провести подсчет вхождений
- :type nested: Iterable
- :param counted_types: типы данных, которые должны быть учтены при подсчете
- :type: counted_types: Iterable
- :return: Объект, реализующий API словаря, содержащий встреченные значения
- :rtype: Counter
- """
- counter = Counter()
- for item in nested:
- # Iterable - служебный тип, обозначающий итерируемый контейнер
- # Если объект контейнер - рекурсивно считаем данные в нем и обновляем текущий счетчик
- if isinstance(item, Iterable) and item.__class__ not in counted_types:
- counter.update(count(item))
- # Если объект из типов, которые должны быть учтены - добавляем элемент к текущему счетчику
- elif item.__class__ in counted_types:
- counter[item] += 1
- # в проитвном случае - пропускаем элемент
- else:
- pass
- return counter
- # Упрощенный вариант, работающий только с list
- def count_simple(nested):
- counter = Counter()
- for item in nested:
- if isinstance(item, list):
- counter.update(count(item))
- else:
- counter[item] += 1
- return counter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement