Most common в питоне

Модуль collections

Python 3 логотип

Модуль collections — предоставляет специализированные типы данных, на основе словарей, кортежей, множеств, списков.

Первым рассматриваемым типом данных будет Counter.

collections.Counter

collections.Counter — вид словаря, который позволяет нам считать количество неизменяемых объектов (в большинстве случаев, строк). Пример:

 )   Но возможности Counter на этом не заканчиваются. У него есть несколько специальных методов:

elements() — возвращает список элементов в лексикографическом порядке.

most_common([n]) — возвращает n наиболее часто встречающихся элементов, в порядке убывания встречаемости. Если n не указано, возвращаются все элементы.

subtract([iterable-or-mapping]) — вычитание

Наиболее часто употребляемые шаблоны для работы с Counter:

  • sum(c.values()) — общее количество.
  • c.clear() — очистить счётчик.
  • list(c) — список уникальных элементов.
  • set(c) — преобразовать в множество.
  • dict(c) — преобразовать в словарь.
  • c.most_common()[:-n:-1] — n наименее часто встречающихся элементов.
  • c += Counter() — удалить элементы, встречающиеся менее одного раза.

Counter также поддерживает сложение, вычитание, пересечение и объединение:

Следующими на очереди у нас очереди (deque)

collections.deque

collections.deque(iterable, [maxlen]) — создаёт очередь из итерируемого объекта с максимальной длиной maxlen. Очереди очень похожи на списки, за исключением того, что добавлять и удалять элементы можно либо справа, либо слева.

Методы, определённые в deque:

append(x) — добавляет x в конец.

appendleft(x) — добавляет x в начало.

clear() — очищает очередь.

count(x) — количество элементов, равных x.

extend(iterable) — добавляет в конец все элементы iterable.

extendleft(iterable) — добавляет в начало все элементы iterable (начиная с последнего элемента iterable).

pop() — удаляет и возвращает последний элемент очереди.

popleft() — удаляет и возвращает первый элемент очереди.

remove(value) — удаляет первое вхождение value.

reverse() — разворачивает очередь.

rotate(n) — последовательно переносит n элементов из начала в конец (если n отрицательно, то с конца в начало).

collections.defaultdict

collections.defaultdict ничем не отличается от обычного словаря за исключением того, что по умолчанию всегда вызывается функция, возвращающая значение:

collections.OrderedDict

collections.OrderedDict — ещё один похожий на словарь объект, но он помнит порядок, в котором ему были даны ключи. Методы:

popitem(last=True) — удаляет последний элемент если last=True, и первый, если last=False.

move_to_end(key, last=True) — добавляет ключ в конец если last=True, и в начало, если last=False.

collections.namedtuple()

Класс collections.namedtuple позволяет создать тип данных, ведущий себя как кортеж, с тем дополнением, что каждому элементу присваивается имя, по которому можно в дальнейшем получать доступ:

Для вставки кода на Python в комментарий заключайте его в теги

  • Книги о Python
  • GUI (графический интерфейс пользователя)
  • Курсы Python
  • Модули
  • Новости мира Python
  • NumPy
  • Обработка данных
  • Основы программирования
  • Примеры программ
  • Типы данных в Python
  • Видео
  • Python для Web
  • Работа для Python-программистов

Источник

Most common в питоне

Last updated: Feb 22, 2023
Reading time · 8 min

banner

# Table of Contents

# Find the most common element in a List in Python

To find the most common element in a list:

  1. Use the collections.Counter() class to create a counter object.
  2. Use the most_common() method to get the most common element in the list.
Copied!
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) most_common = counter.most_common(1)[0][0] print(most_common) # 👉️ one most_common_2 = counter.most_common(2) print(most_common_2) # 👉️ [('one', 3), ('two', 2)]

If you need to find the least common element in a list, click on the following subheading.

We used the collections.Counter class to count the occurrences of each list item.

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

Copied!
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) print(counter) # 👉️ Counter()

Counter objects implement a most_common() method that returns a list of the N most common elements and their counts from the most common to the least.

Copied!
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) most_common = counter.most_common(1)[0][0] print(most_common) # 👉️ one # 👇️ [('one', 3)] print(counter.most_common(1))

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) - 1 .

If no argument is provided to the most_common method, it lists all element counts.

The method returns a list of tuples where the first element is the list item and the second is the number of occurrences.

# Finding the most common N elements in a list

You can also use this approach to get the most common N elements in a list.

Copied!
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) n = 2 most_common_n = counter.most_common(n) print(most_common_n) # 👉️ [('one', 3), ('two', 2)]

We passed 2 as an argument to the most_common() method, so it returned the most common 2 elements in the list.

Alternatively, you can use the max() function.

# Find the most common element in a List using max()

This is a four-step process:

  1. Use the max() function.
  2. Pass the key argument to the functions.
  3. Use the list.count() method to count the occurrences of each element.
  4. The max() function will return the most common element.
Copied!
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = max(set(a_list), key=a_list.count) print(most_common) # 👉️ one

We used the max() function to get the most common element in a list.

The max function returns the largest item in an iterable or the largest of two or more arguments.

Copied!
my_list = [15, 45, 30] result = max(my_list) print(result) # 👉️ 45

The max function also takes an optional key argument.

We used the set() class to convert the list to a set object to remove any duplicates.

  1. The list.count() method gets called with each element in the set .
  2. The method returns the number of times the element appears in the list.
  3. The max() function returns the most common list element.
Copied!
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = max(set(a_list), key=a_list.count) print(most_common) # 👉️ one

The list.count() method takes a value and returns the number of times the provided value appears in the list.

Copied!
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] print(a_list.count('one')) # 👉️ 3 print(a_list.count('two')) # 👉️ 2 print(a_list.count('abc')) # 👉️ 0

# Find the most common element in a List using statistics.mode()

Alternatively, you can use the statistics.mode() method.

The mode() method returns the single most common value in the provided iterable.

Copied!
from statistics import mode a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = mode(a_list) print(most_common) # 👉️ one

The statistics.mode method takes an iterable and returns the most common value in the iterable.

Copied!
from statistics import mode a_list = ['one', 'one', 'one', 'two', 'two', 'three'] print(mode([1, 1, 1, 2, 2, 3])) # 👉️ 1 # 👇️ one print(mode(['one', 'one', 'one', 'two', 'two', 'three']))

If there are multiple values with the same frequency, the method returns the first encountered value.

If the provided iterable is empty, the method raises a StatisticsError exception.

Prior to Python v3.8, the statistics.mode() method raises a StatisticsError exception if there is no most common element in the iterable, e.g. if the top two have the same number of occurrences.

# Get the least common element in a List in Python

To get the least common element in a list:

  1. Use the collections.Counter() class to count the occurrences of each element.
  2. Use the most_common() method to get the most common elements and their counts.
  3. Access the result at index -1 to get the least common element.
Copied!
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # ✅ Get the least common element in a list least_common = Counter(a_list).most_common()[-1] print(least_common) # 👉️ ('c', 1) print(least_common[0]) # 👉️ 'c' # ------------------------------------------------- # ✅ Get the N least common elements in a list least_common_2_elements = Counter(a_list).most_common()[-2:] print(least_common_2_elements) # 👉️ [('b', 2), ('c', 1)]

We used the collections.Counter class to count the occurrences of each list item.

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

Copied!
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # 👇️ Counter() print(Counter(a_list))

Counter objects implement a most_common() method that returns a list of the N most common elements and their counts from the most common to the least.

Copied!
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # 👇️ [('z', 3), ('a', 2), ('b', 2), ('c', 1)] print(Counter(a_list).most_common())

We didn't provide an argument for N, so the method returns all elements in the counter.

Elements that have equal counts are ordered by the first encountered value.

The last step is to access the list at index -1 .

Copied!
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] least_common = Counter(a_list).most_common()[-1] print(least_common) # 👉️ ('c', 1) print(least_common[0]) # 👉️ 'c'

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) - 1 .

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

The list element at index -1 stores the least common item and its number of occurrences in the list.

# Find the N least common elements in a list

You can use list slicing if you need to get the N least common elements in the list.

Copied!
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] least_common_2_elements = Counter(a_list).most_common()[-2:] print(least_common_2_elements) # 👉️ [('b', 2), ('c', 1)]

The syntax for list slicing is my_list[start:stop:step] .

The start index is inclusive and the stop index is exclusive (up to, but not including).

The slice my_list[-2:] starts at the second to last list item and goes to the end of the list.

# Find the most frequent value in a Dictionary in Python

To find the most frequent value in a dictionary:

  1. Use the dict.values() method to get a view of the dictionary's values.
  2. Use the collections.Counter() class to create a counter object.
  3. Use the most_common() method to get the most frequent value in the dictionary.
Copied!
from collections import Counter my_dict = 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 > counter = Counter(my_dict.values()) most_common_value = counter.most_common(1)[0] print(most_common_value) # 👉️ (1, 3) print(most_common_value[0]) # 👉️ 1 most_common_values = counter.most_common(2) print(most_common_values) # 👉️ [(1, 3), (2, 2)]

Источник

Читайте также:  Json encode date php
Оцените статью