【问题标题】:Why the function doesn't sucsses to sort the list right?为什么该函数不能对列表进行正确排序?
【发布时间】:2022-11-22 22:31:45
【问题描述】:

我尝试构建一个函数来检测一个字谜是一个单词列表,并根据它们在第一个列表中的位置返回所有字谜的列表。 例如: 输入: ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts'] 输出:[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]

我的代码是这样的:

def sort_anagrams(list_of_strings):
    #list_of_strings = tuple(list_of_strings)
    #print(list_of_strings)
    sorted_list_of_anagrams =[]
    
    for word_1 in list_of_strings:
        local_list = []
        if word_1 in local_list:
            for word_2 in list_of_strings:
                if is_anagrams(word_1, word_2) == True:
                    local_list.append(word_2)
        else:
            local_list.append(word_1)
            for word_2 in list_of_strings:
                if is_anagrams(word_1, word_2) == True:
                    local_list.append(word_2)
        local_list = sorted(local_list)
        if sorted(local_list) in sorted(sorted_list_of_anagrams):
            pass 
        else:
            sorted_list_of_anagrams.append(local_list)
    print(sorted_list_of_anagrams)                  
    #return sorted_list_of_anagrams
    

def is_anagrams(str_1, str_2):
    return str_1 != str_2 and sorted(str_1) == sorted(str_2)

def create_anagram_list(anagram_list):
    anagram_list = list(anagram_list)
    print(anagram_list)


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

它给了我字谜,但顺序不正确。例如:['resmelts', 'smelters', 'termless']而不是['smelters', 'termless', 'resmelts']

【问题讨论】:

  • Python 2 已于 2020 年停产。如果您只是刚刚学习,可能会关注该语言当前支持和推荐的版本,即 Python 3。

标签: python python-2.7


【解决方案1】:

这是有问题的代码:

        local_list = sorted(local_list)
        if sorted(local_list) in sorted(sorted_list_of_anagrams):

由于 sorted_list_of_anagrams 是一个列表列表,当您对其进行排序时,它不会单独对每个内部列表进行排序,而只会对外部列表进行排序。这应该工作:

if sorted(local_list) in [sorted(lst) for lst in sorted_list_of_anagrams]:

还要确保删除它上面的行local_list = sorted(local_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多