简体   繁体   中英

lists of anagrams in python using two for loops

I need to write a function that takes a list of strings, and return a list that have lists of anagrams words. I need to use 2 for loops for that exercise. Words that are not anagrams to anything will be one item list inside the big list

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

im getting the items sorted but dont know how to continue... heres my code:

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))

This program would give the result for the list you pass. edit: I have replace lambda with a function, and zip with a for loop!

hours later, i made it (: ill post my answer here if someone will need it in the future. feel kinda stupid this simple thing took me so much time

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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