📜  python permutation - Python (1)

📅  最后修改于: 2023-12-03 15:34:03.237000             🧑  作者: Mango

Python中的排列(permutation)操作

在Python中,有很多方法可以进行排列操作,让我们来一一介绍。

方法1: itertools.permutations()

Python的itertools模块提供了permutations()方法可以用来生成排列。下面是一个示例:

import itertools

my_list = [1, 2, 3]
permutations_list = list(itertools.permutations(my_list))

print(permutations_list)

输出结果为:

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
方法2: 使用递归

我们可以编写自己的递归函数来生成排列。下面给出一个示例代码:

def permutation(lst):
    # If lst is empty then there are no permutations
    if len(lst) == 0:
        return []
    
    # If there is only one element in lst then, only
    # one permutation is possible
    if len(lst) == 1:
        return [lst]

    # Find the permutations for lst if there are
    # more than 1 characters

    l = [] # empty list that will store current permutation

    # Iterate the input(lst) and calculate the permutation
    for i in range(len(lst)):
        m = lst[i]

        # Extract lst[i] or m from the list.  remLst is
        # remaining list
        remLst = lst[:i] + lst[i+1:]

        # Generating all permutations where m is first
        # element
        for p in permutation(remLst):
            l.append([m] + p)
    return l

my_list = [1, 2, 3]
permutations_list = permutation(my_list)

print(permutations_list)

输出结果为:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
方法3: 使用Heap算法

Heap算法可以用来在Python中生成排列。下面给出一个示例代码:

def heap_permute(n, A):
    if n == 1:
        yield A
    else:
        for i in range(n-1):
            for hp in heap_permute(n-1, A):
                yield hp
            j = 0 if (n % 2) == 0 else i
            A[j], A[n-1] = A[n-1], A[j]
        for hp in heap_permute(n-1, A):
            yield hp

my_list = [1, 2, 3]
permutations_list = list(heap_permute(len(my_list), my_list))

print(permutations_list)

输出结果为:

[[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]

总结:

以上是在Python中生成排列(permutation)操作的三种方法。其中,使用itertools.permutations()方法是最简单的方法,也是最常用的方法。如果你想了解更多的排列操作方法,也可以查看Python中的所有排列操作方法