【问题标题】:lists of anagrams in python using two for loopspython中使用两个for循环的字谜列表
【发布时间】:2020-09-20 05:55:25
【问题描述】:

我需要编写一个接受字符串列表的函数,并返回一个包含字谜单词列表的列表。我需要为该练习使用 2 个 for 循环。不是任何东西的字谜的单词将是大列表中的一个项目列表

示例输出:

>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'],
 ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], 
['smelters', 'termless', 'resmelts']] 

我正在整理项目,但不知道如何继续...这是我的代码:

def sort_anagrams(list_of_strings):
    sorted_list = list()
    temp_list = list()
    temp2_list = list()
    for item in list_of_strings:
        temp_list.append("".join(sorted(item)))
    print(temp_list)

【问题讨论】:

  • 你尝试过什么,你在哪里卡住了?提供一个有效的minimal reproducible example
  • @Tomerikoo 我编辑了帖子
  • 好的,那么您知道如何确定字谜吗?你试过搜索这个问题吗?
  • 好吧,我需要对它们进行排序并在之后对其进行比较.. 我尝试搜索它,但没有找到包含 2 个 for 循环的东西(我正在参加在线课程,他们要求那种解决方案)

标签: python python-3.x


【解决方案1】:
def sort_anagrams(l):
    a,u,x,m=[],[],[],[]
    for i in l:
         i=''.join(sorted(i))
         a.append(i)
    for i in range(len(l)):
         m.append([l[i],a[i]])
    d=list((pair[0],pair[1]) for pair in m)  
    def sorting(s):
        return s[1]

    d=sorted(d, key=sorting)
    count=0
    for i in d:
        if i[1] not in x:
            x.append(i[1])
            u.insert(count,list(list([i[0]])))    
            count+=1
        else:
            u[count-1].append(i[0])    # grouping anagrams together
    return(u)

l = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

print(sort_anagrams(l))

这个程序会给出你通过的列表的结果。 编辑:我用函数替换 lambda,用 for 循环替换 zip!

【讨论】:

  • 感谢您的帮助,但是没有教过 lambda 和 zip,所以我不应该使用它。课程论坛上有人告诉我们需要嵌套循环
【解决方案2】:

几小时后,我成功了(: 如果将来有人需要它,我会在这里发布我的答案。感觉有点傻这个简单的事情花了我这么多时间

def sort_anagrams(list_of_strings):
    sorted_list = list()

    for item in list_of_strings:
        temp_list = list()
        for num in range(len(list_of_strings)):
            if sorted(item) == sorted(list_of_strings[num]) and (item not in sorted_list):
                temp_list.append(list_of_strings[num])
        sorted_list.append(temp_list)

    return(duplicate_remove(sorted_list))


def duplicate_remove(list_to_check):
    final_list = []
    for item in list_to_check:
        if item not in final_list:
            final_list.append(item)
    return final_list

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2019-12-11
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多