python - 如何在纯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
很感谢任何形式的帮助。
解决方案
您可以使用带有键的字典作为排序词
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']]
推荐阅读
- drupal - 当我们在 Drupal 8 中卸载模块时如何删除自定义实体字段?
- html - 将悬停时的阴影效果添加到 DIV 框
- swift - 如何快速打印大量 10 次方 25 中的所有数字?
- javascript - Office.js 协作处理文档
- java - ImageIO.read(); 悬挂
- r - 在分隔符上拆分字符串,在拆分之前保留分隔符
- powershell - get-aduser 证书奇怪的错误
- javascript - 如何使用jquery动态传递id
- jmeter - 如何根据先前请求中提供的日/月/年值计算年龄?- Jmeter
- c# - 是否有代码注释将 XML 属性限制为枚举值?