我正在编写一个程序,从单词列表中找到字谜并输出不同列表中的字谜但按字母顺序排列

时间:2015-05-15 08:40:02

标签: python list alphabetical

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)

输出结果为:

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

我希望输出为:

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

如何更改代码以获得正确的输出?

2 个答案:

答案 0 :(得分:4)

使用sorted

打印前对new_list进行排序
for i in sorted(new_list):
    i.sort()
    print(i)

这将按预期打印输出

答案 1 :(得分:1)

在创建单词之前排序:

from collections import OrderedDict
some_list.sort()
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
   ...........