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

Один из способов решения этой задачи – использовать словарь. Можно создать словарь, в котором каждому элементу списка соответствует количество его повторений, и в цикле перебрать элементы списка, добавляя их в словарь.

Вот пример такой функции:

def count_repeats(lst):
    """
    Возвращает словарь, в котором каждому элементу списка lst соответствует
    количество его повторений.
    """
    repeats = {}
    for item in lst:
        if item in repeats:
            repeats[item] += 1
        else:
            repeats[item] = 1
    return repeats



# Пример использования функции
lst = [10, 10, 23, 10, 123, 66, 78, 123]
repeats = count_repeats(lst)
print(repeats)  # {10: 3, 123: 2}

Функция count_repeats принимает на вход список lst, перебирает его элементы и добавляет их в словарь repeats. Если элемент уже есть в словаре, то увеличивается значение соответствующей пары ключ-значение, если же элемента еще нет в словаре, то добавляется пара с ключом равным этому элементу и значением 1.

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


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

Вот пример кода, который использует функцию Counter:

from collections import Counter

def count_repeats(lst):
    """
    Возвращает словарь, в котором каждому элементу списка lst соответствует
    количество его повторений.
    """
    return Counter(lst)


# Пример использования функции
lst = [10, 10, 23, 10, 123, 66, 78, 123]
repeats = count_repeats(lst)
print(repeats)  # Counter({10: 3, 123: 2})

В этом коде сначала импортируется модуль collections и функция Counter, а затем определяется функция count_repeats, которая принимает список lst и возвращает результат вызова функции Counter на этом списке.


Вы также можете использовать функцию most_common из модуля collections, чтобы найти топ-N самых часто встречающихся элементов в списке. Эта функция принимает список и число N, и возвращает список кортежей, каждый из которых содержит элемент и количество его повторений.

Вот пример кода, который использует функцию most_common:

from collections import Counter

def find_top_repeats(lst, n):
    """
    Возвращает топ-N самых часто встречающихся элементов в списке lst.
    """
    return Counter(lst).most_common(n)


# Пример использования функции
lst = [10, 10, 23, 10, 123, 66, 78, 123]
top_repeats = find_top_repeats(lst, 2)
print(top_repeats)  # [(10, 3), (123, 2)]

В этом коде сначала импортируется модуль collections и функция Counter, а затем определяется функция find_top_repeats, которая принимает список lst и число n, и возвращает результат вызова функции most_common


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

Вот пример кода, который использует функцию set:

def find_unique(lst):
    """
    Возвращает список уникальных элементов в списке lst.
    """
    return list(set(lst))


# Пример использования функции
lst = [10, 10, 23, 10, 123, 66, 78, 123]
unique = find_unique(lst)
print(unique)  # [66, 78, 10, 123, 23]

В этом коде определяется функция find_unique, которая принимает список lst и возвращает список уникальных элементов. Для этого список преобразуется в множество


Если вам нужно найти только уникальные элементы в списке и посчитать их количество, то можете соединить два предыдущих подхода: сначала использовать функцию set для нахождения уникальных элементов, а затем функцию count_repeats для подсчета их количества.

Вот пример кода, который реализует этот подход:

def count_unique(lst):
    """
    Возвращает словарь, в котором каждому уникальному элементу списка lst соответствует
    количество его повторений.
    """
    repeats = {}
    for item in set(lst):
        repeats[item] = lst.count(item)
    return repeats


# Пример использования функции
lst = [10, 10, 23, 10, 123, 66, 78, 123]
unique_counts = count_unique(lst)
print(unique_counts)  # {66: 1, 78: 1, 10: 3, 123: 2}

В этом коде определяется функция count_unique, которая принимает список lst и возвращает словарь, в котором каждому уникальному элементу списка

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!

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:

# Finding Duplicate Items in a Python List
numbers = [1, 2, 3, 2, 5, 3, 3, 5, 6, 3, 4, 5, 7]

duplicates = [number for number in numbers if numbers.count(number) > 1]
unique_duplicates = list(set(duplicates))

print(unique_duplicates)

# Returns: [2, 3, 5]

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:

# Finding Duplicate Items in a Python List and Count Them
from collections import Counter
numbers = [1, 2, 3, 2, 5, 3, 3, 5, 6, 3, 4, 5, 7]

counts = dict(Counter(numbers))
duplicates = {key:value for key, value in counts.items() if value > 1}
print(duplicates)

# Returns: {2: 2, 3: 4, 5: 3}

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:

# Remove Duplicates from a List in Python
from collections import Counter
numbers = [1, 2, 3, 2, 5, 3, 3, 5, 6, 3, 4, 5, 7]
unique = list(set(numbers))
print(unique)

# Returns: [1, 2, 3, 4, 5, 6, 7]

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:

# Remove Duplicates from a List of Dictionaries
items = [{'name':'Nik'}, {'name': 'Kate'}, {'name':'James'}, {'name':'Nik'}, {'name': 'Kate'}]
unique_items = []

for item in items:
    if item not in unique_items:
        unique_items.append(item)
print(unique_items)

# Returns: [{'name': 'Nik'}, {'name': 'Kate'}, {'name': 'James'}]

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:

# Remove Duplicates from a List of Lists in Python
list_of_lists = [[1,2,3], [1,2], [2,3], [1,2,3], [2,3], [1,2,3,4]]
unique = []

for sublist in list_of_lists:
    if sublist not in unique:
        unique.append(sublist)

print(unique)

# Returns: [[1, 2, 3], [1, 2], [2, 3], [1, 2, 3, 4]]

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.

Additional Resources

To learn about related topics, check out the tutorials below:

  • Python: Combine Lists – Merge Lists (8 Ways)
  • Python: Count Number of Occurrences in List (6 Ways)
  • Python List Difference: Find the Difference between 2 Python Lists

simplest way without any intermediate list using list.index():

z = ['a', 'b', 'a', 'c', 'b', 'a', ]
[z[i] for i in range(len(z)) if i == z.index(z[i])]
>>>['a', 'b', 'c']

and you can also list the duplicates itself (may contain duplicates again as in the example):

[z[i] for i in range(len(z)) if not i == z.index(z[i])]
>>>['a', 'b', 'a']

or their index:

[i for i in range(len(z)) if not i == z.index(z[i])]
>>>[2, 4, 5]

or the duplicates as a list of 2-tuples of their index (referenced to their first occurrence only), what is the answer to the original question!!!:

[(i,z.index(z[i])) for i in range(len(z)) if not i == z.index(z[i])]
>>>[(2, 0), (4, 1), (5, 0)]

or this together with the item itself:

[(i,z.index(z[i]),z[i]) for i in range(len(z)) if not i == z.index(z[i])]
>>>[(2, 0, 'a'), (4, 1, 'b'), (5, 0, 'a')]

or any other combination of elements and indices….

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

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

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

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    dup = [x for i, x in enumerate(nums) if i != nums.index(x)]

    print(dup)  # [1, 5, 1]

Скачать  Выполнить код

2. Использование оператора In

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

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    dup = [x for i, x in enumerate(nums) if x in nums[:i]]

    print(dup)  # [1, 5, 1]

Скачать  Выполнить код

3. Использование набора (эффективно)

Чтобы повысить производительность и выполнить работу за линейное время, вы можете использовать set структура данных.

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    visited = set()

    dup = [x for x in nums if x in visited or (visited.add(x) or False)]

    print(dup)  # [1, 5, 1]

Скачать  Выполнить код

 
Чтобы получить каждый дубликат только один раз, вы можете использовать понимание множества, как показано ниже:

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    visited = set()

    dup = {x for x in nums if x in visited or (visited.add(x) or False)}

    print(dup)  # {1, 5}

Скачать  Выполнить код

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

Вот альтернативное решение с использованием count() Функция, которая обеспечивает простой и понятный способ выявления дубликатов в списке. Это не рекомендуется для больших списков, поскольку временная сложность является квадратичной.

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    dup = {x for x in nums if nums.count(x) > 1}

    print(dup)  # {1, 5}

Скачать  Выполнить код

5. Использование iteration_utilities модуль

Наконец, iteration_utilities модуль предлагает duplicates функция, которая дает повторяющиеся элементы. Вы можете использовать это как:

from iteration_utilities import duplicates

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    dup = list(duplicates(nums))

    print(dup)        # [1, 5, 1]

 
Чтобы получить каждый дубликат только один раз, объедините его с unique_everseen():

from iteration_utilities import unique_everseen

if __name__ == ‘__main__’:

    nums = [1, 5, 2, 1, 4, 5, 1]

    dup = unique_everseen(duplicates(nums))

    print(dup)        # [1, 5]

Это все, что касается поиска повторяющихся элементов в списке в Python.

 
Также см:

Удалить повторяющиеся значения из списка Python

Содержание

  1. Введение
  2. Поиск одинаковых элементов в списке с помощью словаря
  3. Поиск одинаковых элементов в списке с помощью модуля collections
  4. Поиск одинаковых элементов в списке с помощью функции filter()
  5. Заключение

Введение

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

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

Для начала создадим неупорядоченный список с числами и пустой словарь:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]
duplicate_elements = {}

Теперь пройдёмся по нашему неупорядоченному списку при помощи цикла for. Внутри цикла добавим условие, что если итерабельный элемент присутствует в словаре duplicate_elements, то прибавляем к значению ключа единицу, т.к. этот элемент уже присутствует в словаре, и был найден его дубликат. Если же условие оказалось ложным, то сработает else, где в словарь будет добавляться новый ключ, которого в нём ранее не было:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]
duplicate_elements = {}

for item in unordered_list:
    if item in duplicate_elements:
        duplicate_elements[item] += 1
    else: 
        duplicate_elements[item] = 1

Выведем результат:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]
duplicate_elements = {}

for item in unordered_list:
    if item in duplicate_elements:
        duplicate_elements[item] += 1
    else: 
        duplicate_elements[item] = 1

print(duplicate_elements)

# Вывод: {6: 2, 8: 1, 7: 2, 5: 2, 1: 1, 4: 2}

В выводе мы видим, что было найдено две шестёрки, одна восьмёрка, две семёрки, две пятёрки, одна единица и две четвёрки.

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

В данном способе для поиска одинаковых элементов в неупорядоченном списке мы будем использовать модуль collections, а точнее класс Counter из него. Сам модуль входит в стандартную библиотеку Python, поэтому устанавливать его не придётся.

Для начала импортируем сам модуль collections и добавим неупорядоченный список:

import collections

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]

Далее при помощи класса Counter из модуля collections подсчитаем количество повторяющихся элементов:

import collections

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]
count_frequency = collections.Counter(unordered_list)

Выведем результат в виде словаря:

import collections

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]
count_frequency = collections.Counter(unordered_list)
print(dict(count_frequency))

# Вывод: {6: 2, 8: 1, 7: 2, 5: 2, 1: 1, 4: 2}

Поиск одинаковых элементов в списке с помощью функции filter()

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

При помощи функции filter() отфильтруем наш список. Внутри неё анонимной функцией lambda будем производить проверку поэлементно, и если определённый элемент встречается больше одного раза, мы добавляем его в count_frequency:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]

count_frequency = filter(lambda x: unordered_list.count(x) > 1, unordered_list)

При помощи функции set() преобразуем полученные данные в count_frequency в множество, а множество в список:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]

count_frequency = filter(lambda x: unordered_list.count(x) > 1, unordered_list)
count_frequency = list(set(count_frequency))

Выведем полученный результат:

unordered_list = [6, 6, 8, 7, 5, 1, 4, 5, 4, 7]

count_frequency = filter(lambda x: unordered_list.count(x) > 1, unordered_list)
count_frequency = list(set(count_frequency))

print(count_frequency)

# Вывод: [4, 5, 6, 7]

Т.е. в неупорядоченном списке повторяются четвёрки, пятёрки, шестёрки и семёрки.

Заключение

В ходе статьи мы с Вами разобрали целых три способа нахождения повторяющихся элементов в списке Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

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