python输出列表元素所有排列形式

例如:[‘a’, ‘b’, ‘c’] 输出 [‘a’, ‘b’, ‘c’] [‘a’, ‘c’, ‘b’] [‘b’, ‘a’, ‘c’] [‘b’, ‘c’, ‘a’] [‘c’, ‘a’, ‘b’] [‘c’, ‘b’, ‘a’]
方法一:利用递归的方式实现

def  permutation(li):
    len_list = len(li)
    if len_list == 1:
        return li

    result = []
    for i in range(len_list):
        res_list = li[:i] + li[i+1:]
        s = li[i]
        per_result = permutation(res_list)
        if len(per_result) == 1:
            result.append(li[i:i + 1] + per_result)
        else:
            result += [[s] + j for j in per_result]
    return result

方法二:利用python自带的模块

import itertools

def permutation(li):
    print(list(itertools.permutations(li)))

你可能感兴趣的:(算法)