Created
January 27, 2015 19:09
-
-
Save jeff1evesque/46346e4daf85c12a0c38 to your computer and use it in GitHub Desktop.
Duplicate List Index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## duplicate_list_index: given a list, return a dictionary, with the 'key' being the list | |
# elements (unique, not duplicated), and the corresponding dictionary | |
# 'value' being a list containing the index location of each instance. | |
# | |
# for example: | |
# list_to_check = list('ABRACADABR') | |
# | |
# then, this method would return the following dictionary: | |
# {'A': [0, 3, 5, 7], 'R': [2, 9], 'B': [1, 8], 'C': [4], 'D': [6]} | |
def duplicate_list_index(list_to_check): | |
# store each element instance into dictionary | |
dict_duplicates = collections.defaultdict(list) | |
for key, value in enumerate(list_to_check): | |
dict_duplicates[value].append(key) | |
# remove non-duplicates from dictionary | |
for key, value in dict_duplicates.items(): | |
if ( len(value) <= 1 ): | |
del dict_duplicates[key] | |
return dict_duplicates |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment