Your problem is that you loop one time over your list ,since you need to loop based on all of the words.
But i suggest another way for this task,you can use itertools.groupby
and sorted function using operator.itemgetter
:
some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']
from operator import itemgetter
from itertools import groupby
s=sorted([(i,''.join(sorted(j))) for i,j in enumerate(some_list)],key=itemgetter(1))
inds= [zip(*g)[0] for _,g in groupby(s,itemgetter(1))]
print [itemgetter(*i)(some_list) for i in inds]
Result :
[('bad', 'dab', 'bda', 'dba'), 'mad', ('sad', 'das'), ('app', 'ppa'), 'pge']
All that i have done here is creating a list of sorted words with those index using sorted
and enumerate
:
sorted([(i,''.join(sorted(j))) for i,j in enumerate(some_list)],key=itemgetter(1))
[(0, 'abd'), (4, 'abd'), (6, 'abd'), (9, 'abd'), (3, 'adm'), (2, 'ads'), (8, 'ads'), (1, 'app'), (7, 'app'), (5, 'egp')]
then we need to grouping this pairs based on the second element and get the first element (indices) so we will have the following list of tuples :
[(0, 4, 6, 9), (3,), (2, 8), (1, 7), (5,)]
that each tuple is contain the indices of the words that those sorted representations are same.
and at last all you need is picking up the elements of the main list based on the preceding indices :
[itemgetter(*i)(some_list) for i in inds]
[('bad', 'dab', 'bda', 'dba'), 'mad', ('sad', 'das'), ('app', 'ppa'), 'pge']