2
some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']

new_list = []
from collections import OrderedDict
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
    temp = []
    for s in some_list:
        if ele == ''.join(sorted(s)):
            temp.append(s)
    if len(temp) > 1:
        new_list.append(temp)

for i in new_list:
    i.sort()
    print(i)

The output is:

  • ['bad', 'bda', 'dab', 'dba']
  • ['app', 'ppa']
  • ['das', 'sad']

I want the output to be:

  • ['app', 'ppa']
  • ['bad', 'bda', 'dab', 'dba']
  • ['das', 'sad']

How do I change the code to get the right output?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
pk.
  • 99
  • 3
  • 12
  • duplicate? http://stackoverflow.com/questions/30246225/create-lists-of-anagrams-from-a-list-of-words – dermen May 15 '15 at 09:08

2 Answers2

4

sort your new_list before printing using sorted

for i in sorted(new_list):
    i.sort()
    print(i)

This will print your output as expected

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

sort before you create the words:

from collections import OrderedDict
some_list.sort()
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
   ...........
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321