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']
如何更改代码以获得正确的输出?
答案 0 :(得分:4)
答案 1 :(得分:1)
在创建单词之前排序:
from collections import OrderedDict
some_list.sort()
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
...........