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

Есть список, и мне нужно знать индекс определенного элемента.
Например:

wordToCheck = "Маша"
list = ['Маша', 'Саша', 'Маша', 'Петя', 'Ваня', 'Маша']

То есть в данном списке, мне нужны индексы — 0, 2, 5

Miron's user avatar

Miron

3,0172 золотых знака13 серебряных знаков32 бронзовых знака

3

Если нужны индексы именно элементов «Маша»:

s = ['Маша', 'Саша', 'Маша', 'Петя', 'Ваня', 'Маша']

x = [i for i, ltr in enumerate(s) if ltr == "Маша"]
print(x)   #  [0, 2, 5]

ответ дан 19 янв 2020 в 8:38

whizz169's user avatar

whizz169whizz169

1,5961 золотой знак4 серебряных знака14 бронзовых знаков

Здесь можно создать словарь, в котором по ключу будут храниться список с индексами

a = {}
index = 0

mlist = ['Маша', 'Саша', 'Маша', 'Петя', 'Ваня', 'Маша', 'Ваня', 'Саша']

for i in mlist:
    if i in a:
        a[i].append(index)
    else:
        a[i] = [index]

    index += 1

for i in a.keys():
    if len(a[i]) > 1:
        print(a[i])

ответ дан 19 янв 2020 в 6:06

Gari's user avatar

GariGari

4343 серебряных знака9 бронзовых знаков

6

mlist = ['Маша', 'Саша', 'Маша', 'Петя', 'Ваня', 'Маша', 'Ваня', 'Саша']
wordToCheck = "Маша"
a = {}
index = 0
count = 0

for i in mlist:
  if wordToCheck == i:
    a[index] = count
    index += 1
  count += 1
print(a)

Вывод:

{0: 0, 1: 2, 2: 5}

ответ дан 19 янв 2020 в 6:39

Miron's user avatar

MironMiron

3,0172 золотых знака13 серебряных знаков32 бронзовых знака

x:= [i for i, x in enumerate(lst) if lst.count(x) > 1]

aleksandr barakin's user avatar

ответ дан 20 авг 2022 в 21:21

Изотов Марк's user avatar

1

You want to pass in the optional second parameter to index, the location where you want index to start looking. After you find each match, reset this parameter to the location just after the match that was found.

def list_duplicates_of(seq,item):
    start_at = -1
    locs = []
    while True:
        try:
            loc = seq.index(item,start_at+1)
        except ValueError:
            break
        else:
            locs.append(loc)
            start_at = loc
    return locs

source = "ABABDBAAEDSBQEWBAFLSAFB"
print(list_duplicates_of(source, 'B'))

Prints:

[1, 3, 5, 11, 15, 22]

You can find all the duplicates at once in a single pass through source, by using a defaultdict to keep a list of all seen locations for any item, and returning those items that were seen more than once.

from collections import defaultdict

def list_duplicates(seq):
    tally = defaultdict(list)
    for i,item in enumerate(seq):
        tally[item].append(i)
    return ((key,locs) for key,locs in tally.items() 
                            if len(locs)>1)

for dup in sorted(list_duplicates(source)):
    print(dup)

Prints:

('A', [0, 2, 6, 7, 16, 20])
('B', [1, 3, 5, 11, 15, 22])
('D', [4, 9])
('E', [8, 13])
('F', [17, 21])
('S', [10, 19])

If you want to do repeated testing for various keys against the same source, you can use functools.partial to create a new function variable, using a «partially complete» argument list, that is, specifying the seq, but omitting the item to search for:

from functools import partial
dups_in_source = partial(list_duplicates_of, source)

for c in "ABDEFS":
    print(c, dups_in_source(c))

Prints:

A [0, 2, 6, 7, 16, 20]
B [1, 3, 5, 11, 15, 22]
D [4, 9]
E [8, 13]
F [17, 21]
S [10, 19]

В этом посте мы обсудим, как найти повторяющиеся элементы в списке в 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

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

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

Если в списке нет повторяющегося элемента, найдите индекс элемента

x = [2, 5, 6]
for i in x:
    print(x.index(i))

Результат вывода:

0
1
2

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

Вызов внутренних методов напрямую

x = [0, 0, 1, 2, 5, 3, 0, 1, 8, 5]
for i in x:
    print(x.index(i))

Результат вывода:

0
0
2
3
4
5
0
2
8
4

Мы нашли элемент0Нижний индекс всегда первый0Индекс элемента.

Пользовательский метод

x = [0, 0, 1, 2, 5, 3, 0, 1, 8, 5]
x_index = []
for i in range(len(x)):
    if x[i] in x[:i]:
        x_index.append(x_index[-1] + 1)
    else:
        x_index.append(x.index(x[i]))

print(x_index)

Результат вывода:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Понравилась статья? Поделить с друзьями:
  • Как исправить написание клавиатуры
  • Как найти ежевику в лесу
  • Как найти номера телефонов которые звонили
  • Как составить биографию ученого
  • Как найти моменты силы относительно оси