从单词列表创建字谜列表 [英] Create lists of anagrams from a list of words

查看:124
本文介绍了从单词列表创建字谜列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从单词列表中找到字谜的创建列表.我应该在代码或递归中使用另一个循环吗?

I want to find create lists of anagrams from a list of words. Should I use another loop in my code or recursion?

some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']

new_list = [some_list[0]]
i = 0
while i+1 < len(some_list):
    if (''.join(sorted(some_list[0]))) == (''.join(sorted(some_list[i+1]))):
        new_list.append(some_list[i+1])
        i = i+1
    else:
        i = i+1

print(new_list)


  • 我的输出是['bad', 'dab', 'bda', 'dba'].但我也想要更多清单 some_list中的其他字谜.

    • My output is ['bad', 'dab', 'bda', 'dba']. But I also want more lists of other anagrams from some_list.
    • 我希望输出为: -['app', 'ppa'] -['bad', 'dab', 'bda', 'dba'] -['sad', 'das']

      I want the output to be: - ['app', 'ppa'] - ['bad', 'dab', 'bda', 'dba'] - ['sad', 'das']

      推荐答案

      我建议您编写Python,而不是Java或您在此处仿真的任何其他语言.这是您的Python核心代码,具有正常的循环且没有所有不必要的内容:

      I recommend you write Python, not Java or whatever other language you're emulating there. Here's your core code in Python, with normal looping and without all the unnecessary stuff:

      new_list = [some_list[0]]
      for word in some_list[1:]:
          if sorted(some_list[0]) == sorted(word):
              new_list.append(word)
      

      我看不到用于递归的方法,但是是的,您可以在其周围包裹一个外循环以找到其他字谜组.

      I don't see use for recursion, but yes, you could wrap an outer loop around this to find the other anagram groups.

      尽管这是我的方法,但使用有用的 itertools .groupby :

      Though this is how I'd do it, using the helpful itertools.groupby:

      for _, group in groupby(sorted(some_list, key=sorted), sorted):
          group = list(group)
          if len(group) > 1:
              print(group)
      

      打印:

      ['bad', 'dab', 'bda', 'dba']
      ['sad', 'das']
      ['app', 'ppa']
      


      已更改问题的替代解决方案,其中对组进行了排序:


      Alternative solution for the changed question with sorting the groups:

      groups = (list(group) for _, group in groupby(sorted(some_list, key=sorted), sorted))
      print([group for group in sorted(groups) if len(group) > 1])
      

      输出:

      [['app', 'ppa'], ['bad', 'dab', 'bda', 'dba'], ['sad', 'das']]
      

      这篇关于从单词列表创建字谜列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆