首页 > 解决方案 > 如何在纯python中将不同字谜单词的列表拆分为单独的列表?

问题描述

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

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

很感谢任何形式的帮助。

标签: pythonstringlistsplit

解决方案


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

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']]

推荐阅读