简体   繁体   中英

return index of each element in list if it repeats

I was needed to find all indexes of elements if some part of element is repeated (all text without underscore and numbers). I am really newbie in Python and that's why I am using following code:

import re
list = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']
list2 = []
for i in range(len(list)):
  list2.append(str(re.sub('[^a-z,A-Z]','', list[i])))

indexList = []
for i in range(len(list2)):
    if list2.count(list2[i]) > 1:
        indexList.append(i)

for i in range(len(indexList)):
    print(list[indexList[i]]) 

May be you can provide me more elegant procedure ?

import re

list1 = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']    
list2 = list(set([''.join(filter(str.isalpha,s)) for s in list1]))    
print (list2)

=================================================

[''.join(filter(str.isalpha,s)) for s in list1] --> the list without numbers/special characters

list(set())-->removes the duplicate characters 

i hope this 1-liner helps!modified list to list1 so python will not get confused :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM