2

I want to store actual index of Two or more duplicate characters in a list. For that i used index() but it returns the same index of all the duplicate characters. Any other solution for this problem.

MrSoloDolo
  • 406
  • 5
  • 10
  • post the code that you tried. – Debanik Dawn Nov 25 '17 at 13:37
  • Welcome to StackOverflow. Please take the time to read this post how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Nov 25 '17 at 13:39
  • 2
    Possible duplicate of [python - find char in string - can I get all indexes?](https://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes) – Mureinik Nov 25 '17 at 13:40
  • why do you have both [tag:python-2.7] and [tag:python-3.x] tags? – sam-pyt Nov 25 '17 at 13:40
  • Possible duplicate of [Counting repeated characters in a string in Python](https://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python) – Sergey Sklyar Nov 25 '17 at 13:47
  • Title requests string, but body requests list. :-| – AJbotic Apr 29 '20 at 16:29

2 Answers2

4

Let our list and our desired element be defined as follows:

my_list = [1, 3, 2, 4, 3, 3, 5, 3]
desired_element = 3

Then you can use a nice built-in of Python, enumerate():

indexes = [index for index, element in enumerate(my_list) if element == desired_element]
print(indexes)

The output is, as expected [1, 4, 5, 7].


Or, in a nicer format:

def indexes(my_list, desired_element):
    return [index for index, element in enumerate(my_list) if element == desired_element]

And then just call it using indexes(list, element).


If you are looking for efficiency (I doubt you are):

def indexes2(my_list, desired_element):
    for index, element in enumerate(my_list):
        if element == desired_element:
            yield index

For large lists (as far as I have tested), this is 4-5 times faster. Note that this returns a generator, and in order to visualise the result, you must convert it to a list using list(...).

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

Using pandas we can read this to a pd series and do some operations in one go.

import pandas as pd

l = ['a','b','c','a','b']

d = (pd.Series(l)[pd.Series(l).duplicated(keep=False)]
     .reset_index()
     .groupby(0)['index']
     .apply(list)
     .to_dict())

d

Returns:

{'a': [0, 3], 'b': [1, 4]}

Or this:

d = (pd.Series(l)
     .reset_index()
     .groupby(0)['index']
     .apply(lambda x: list(x) if len(list(x)) > 1 else None)
     .dropna()
     .to_dict())
Anton vBR
  • 18,287
  • 5
  • 40
  • 46