-1

我有这个字谜单词列表,如果它们具有相同的字母,我想将它们拆分为嵌套列表。

mylist = ["pots", "stop", "levi",  "vile", "evil", "spot", "star", "rats", "bingo", "live", "tops" "gobin"]

结果:

anagrams = [["pots", "stop", "spot", "tops"],
["levi", "live", "vile", "evil"],
["star", "rats"],
["bingo", "gobin"]]

我想使用纯 python 拆分它们,即不使用任何 python 包,例如来自 itertools 的 groupby

很感谢任何形式的帮助。

4

1 回答 1

4

您可以使用带有键的字典作为排序词

mylist = ["pots", "stop", "levi",  "vile", "evil", "spot", "star", "rats", "bingo", "live", "tops", "gobin"]

res = {}

for i in mylist:
    res.setdefault(tuple(sorted(i)), []).append(i)

print(list(res.values()))

输出

[['pots', 'stop', 'spot', 'tops'], ['levi', 'vile', 'evil', 'live'], ['star', 'rats'], ['bingo', 'gobin']]
于 2021-09-03T15:24:13.947 回答