Перейти к содержимому

Как вывести повторяющиеся элементы в списке python

  • автор:

Найти повторяющиеся элементы в списке Python

В этом посте мы обсудим, как найти повторяющиеся элементы в списке в Python.

1. Использование index() функция

Простое решение состоит в том, чтобы выполнить итерацию по списку с индексами, используя понимание списка, и проверить наличие другого вхождения каждого встреченного элемента, используя index() функция. Временная сложность этого решения будет квадратичной, а код не обрабатывает повторяющиеся элементы в выводе.

Find Duplicates in a Python List

Find Duplicates in a Python List Cover Image

In this tutorial, you’ll learn how to find and work with duplicates in a Python list. Being able to work efficiently with Python lists is an important skill, given how widely used lists are. Because Python lists allow us to store duplicate values, being able to identify, remove, and understand duplicate values is a useful skill to master.

By the end of this tutorial, you’ll have learned how to:

  • Find duplicates in a list, as well as how to count them
  • Remove duplicates in Python lists
  • Find duplicates in a list of dictionaries and lists

Let’s get started!

Table of Contents

How to Find Duplicates in a List in Python

Let’s start this tutorial by covering off how to find duplicates in a list in Python. We can do this by making use of both the set() function and the list.count() method.

The .count() method takes a single argument, the item you want to count, and returns the number of times that item appears in a list. Because of this, we can create a lists comprehension that only returns items that exist more than once. Let’s see how this works and then break it down a bit further:

Let’s break down what we did here:

  1. We used a list comprehension to include any item that existed more than once in the list
  2. We then converted this to a set to remove any duplicates from the filtered list
  3. Finally, we converted the set back to a list

In the next section, you’ll learn how to find duplicates in a Python list and count how often they occur.

How to Find Duplicates in a List and Count Them in Python

In this section, you’ll learn how to count duplicate items in Python lists. This allows you to turn a list of items into a dictionary where the key is the list item and the corresponding value is the number of times the item is duplicated.

In order to accomplish this, we’ll make use of the Counter class from the collections module. We’ll then filter our resulting dictionary using a dictionary comprehension. Let’s take a look at the code and then we’ll break down the steps line by line:

Let’s break this code down, as it’s a little more complex:

  1. We import the Counter class from the collections library
  2. We load our list of numbers
  3. We then create a Counter object of our list and convert it to a dictionary
  4. We then filter our dictionary to remove any key:value pairs where the key only exists a single time

In the next section, you’ll learn how to remove duplicates from a Python list.

How to Remove Duplicates from a List in Python

Removing duplicates in a Python list is made easy by using the set() function. Because sets in Python cannot have duplicate items, when we convert a list to a set, it removes any duplicates in that list. We can then turn the set back into a list, using the list() function.

Let’s see how we can do this in Python:

To learn about other ways you can remove duplicates from a list in Python, check out this tutorial covering many different ways to accomplish this! In the next section, you’ll learn how to find duplicates in a list of dictionaries.

How to Remove Duplicates in a List of Dictionaries in Python

Let’s take a look at how we can remove duplicates from a list of dictionaries in Python. You’ll often encounter data from the web in formats that resembles lists of dictionaries. Being able to remove the duplicates from these lists is an important skill to simplify your data.

Let’s see how we can do this in Python by making using a for a loop:

This method will only include complete duplicates. This means that if a dictionary had, say, an extra key-value pair it would be included.

How to Remove Duplicates in a List of Lists in Python

We can use the same approach to remove duplicates from a list of lists in Python. Again, this approach will require the list to be complete the same for it to be considered a duplicate. In this case, even different orders will be considered unique.

Let’s take a look at what this looks like:

What we do here is loop over each sublist in our list of lists and assess whether the item exists in our unique list. If it doesn’t already exist (i.e., it’s unique so far), then it’s added to our list. This ensures that an item is only added a single time to our list.

Conclusion

In this tutorial, you learned how to work with duplicate items in Python lists. First, you learned how to identify duplicate elements and how to count how often they occur. You then learned how to remove duplicate elements from a list using the set() function. From there, you learned how to remove duplicate items from a list of dictionaries as well as a list of lists in Python.

Being able to work with lists greatly improves your Python programming skills. Because these data structures are incredibly common, being able to work with them makes you a much more confident and capable developer.

To learn more about the Counter class from the collections library, check out the official documentation here.

Поиск и вывод на печать повторяющихся элементов массива Python

В этой программе нам нужно найти и напечатать повторяющиеся элементы, присутствующие в массиве Python. Это можно сделать в два цикла. Первый цикл выберет элемент, а второй цикл будет перебирать массив, сравнивая выбранный элемент с другими элементами. Если совпадение найдено, выведется повторяющийся элемент.

Программа Python для печати повторяющихся элементов массива

В приведенном выше массиве первый дубликат будет найден с индексом 4, который является дубликатом элемента(2), присутствующего в индексе 1. Таким образом, повторяющиеся элементы в приведенном выше массиве — это 2, 3 и 8.

Удаление дубликатов из списка в Python

Есть много способов удалить дубликаты из списка Python:

  • использование временного списка и цикла;
  • использование встроенного метода set();
  • использование ключей словаря;
  • функция List count();
  • понимание списка.

Список в Python может содержать повторяющиеся элементы. Давайте рассмотрим примеры удаления повторяющихся элементов разными способами.

1. Использование временного списка

Это метод для удаления повторяющихся элементов из списка. Мы создадим временный список и добавим в него элементы только в том случае, если его нет.

Результат: обновленный список после удаления дубликатов = [1, 2, 3, 4].

2. Функция set()

В наборе Python нет повторяющихся элементов. Мы можем использовать встроенную функцию set() для преобразования списка в набор, а затем использовать функцию list(), чтобы преобразовать его обратно в список.

3. Перечисление элементов как ключей словаря

Мы знаем, что ключи словаря уникальны. Класс dict имеет функцию fromkeys(), которая принимает итерацию для создания словаря с ключами из итерируемого.

4. Когда функция List count() – не рекомендуется

Метод list count() возвращает количество вхождений значения. Мы можем использовать его с методом remove(), чтобы убрать повторяющиеся элементы из списка.

ПРИМЕЧАНИЕ. Как указано в комментарии ниже, использование функции count() не рекомендуется при удалении элемента из того же итератора, поскольку это может привести к нежелательным результатам.

5. Понимание списка

Мы можем создать список из итерации, используя понимание списка. Этот метод аналогичен использованию временного списка и цикла for для удаления повторяющихся элементов. Но это уменьшает количество строк кода.

Лучший способ удалить дубликаты из списка

Если вам не нужны повторяющиеся элементы, вам следует использовать Set. Но если вам нужно удалить повторяющиеся значения из списка, я бы предпочел функцию count(), потому что она не создает другой временный набор или объект списка. Таким образом, он более эффективен с точки зрения памяти.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *