繁体   English   中英

python 中的字谜列表使用两个 for 循环

[英]lists of anagrams in python using two for loops

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

例如 output:

>>> 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)
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 替换为 function,并将 zip 替换为 for 循环!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM