【问题标题】:How to split a list of different anagram words into separate lists in pure python?如何在纯python中将不同字谜单词的列表拆分为单独的列表?
【发布时间】:2021-11-01 22:24:35
【问题描述】:

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

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

非常感谢任何帮助。

【问题讨论】:

  • 您能否展示您的尝试并具体说明您遇到的问题?
  • 提示:要判断两个字符串是否是字谜,请使用sorted(s1) == sorted(s2)
  • @MichaelRSF 它不用作布尔值,它实际上是根据按字母顺序排序的字符创建一个列表。

标签: python string list split


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2014-11-17
    • 1970-01-01
    • 2021-03-11
    • 2018-05-17
    相关资源
    最近更新 更多