我想做的是,如果我有一个像这样的列表:
["lime", "mile", "liem", "tag", "gat", "goat", "math"]
我想编写一个函数,该函数返回列表中具有字谜的单词,如下所示:
["lime", "mile", "liem", "tag", "gat",]
到目前为止,我有以下代码:
def anagramprinter(x):
output = []
for i in x:
for n in i:
if n in x[i]:
我无法超越这一部分,希望获得一些帮助,并且也希望获得详尽的解释.
谁能告诉我一种不涉及导入的方法?
谢谢
谢谢.
解决方法:
通过字符的冻结集识别单词的方法:
from collections import defaultdict
wordlist = ["lime", "mile", "liem", "tag", "gat", "goat", "math"]
worddict = defaultdict(list)
for word in wordlist:
worddict[frozenset(word)].append(word)
anagrams = [words for words in worddict.values() if len(words) > 1]
print(anagrams)
# [['lime', 'mile', 'liem'], ['tag', 'gat']]
输出结果还不是您想要的,但是如果您愿意的话,将列表弄平很容易.
评论后更新:
上面的解决方案不能很好地处理带有重复字符的单词.但这会(这次字典的键只是由排序字母组成的字符串):
for word in wordlist:
worddict[''.join(sorted(word))].append(word)