如何将排列的输出放入列表中

How to take the output of permutation into a list

我有这段代码可以输出给定单词的所有排列:

def get_permutation(word, base = ""):
    
    if len(word) == 0:
        print(base)
    
    for i in range(len(word)):
        
        newBase = base + word[i]
        newWord = word[0:i] + word[i + 1:]
        
        get_permutation(newWord, newBase)

我想将输出保存到一个列表中,该列表在此函数结束后返回。 这可能很简单,但我是 python 的初学者,所以我不知道如何

我已经找到答案了:

answer = [ ]

def get_permutation(word, base = ""):
    
    if len(word) == 0:
        answer.append(base)
    
    for i in range(len(word)):
        
        newBase = base + word[i]
        newWord = word[0:i] + word[i + 1:]
        
        get_permutation(newWord, newBase)
    
    return answer

唯一的问题是列表是垂直打印的?

如果您想要一个 returns 整个列表的函数,可以按如下方式完成。

def get_permutations_list(word, base = ""):    

    lst = [] #Create a list to hold permutations.

    def get_permutation(word, base):

        if len(word) == 0:
            lst.append(base) #Add current permutation to end of list.

        for i in range(len(word)):

            newBase = base + word[i]
            newWord = word[0:i] + word[i + 1:]

            get_permutation(newWord, newBase)

    get_permutation(word, base) #Run the recursive function.
    
    return lst #Return the completed list.