Python 生成集合的所有排列组合

Python 生成集合的所有排列组合

将集合的所有成员按一定顺序或序列进行排列,并且如果集合已经有序,则重新排列(重新排序)其元素称为排列。

使用for循环生成所有排列组合

我们将使用for循环生成排列组合 –

示例

def permutFunc(myList):

    # No permutations for empty list
    if len(myList) == 0:
        return []

    # Single permutation for only one element
    if len(myList) == 1:
        return [myList]

    # Permutations for more than 1 characters
    k = []

    # Looping
    for i in range(len(myList)):
        m = myList[i]
        res = myList[:i] + myList[i+1:]
        for p in permutFunc(res):
            k.append([m] + p)
    return k

# Driver program
myList = list('456')
for p in permutFunc(myList):
    print (p)

输出

['4', '5', '6']
['4', '6', '5']
['5', '4', '6']
['5', '6', '4']
['6', '4', '5']
['6', '5', '4']

使用permutations()函数生成所有排列

我们将使用permutations()函数生成排列 –

示例

from itertools import permutations

# Using the permutations() method
myList = list(permutations(range(1, 3)))

# Display the Permutations
print("Permutations\n",myList)

输出

Permutations
[(1, 2), (2, 1)]

使用permutations()和extend()函数生成所有排列

使用extend()函数生成所有排列的方法如下−

示例

import itertools

myList = [2,3,4]

resList = []

for i in range(1,len(myList)+1):
    resList.extend(list(itertools.permutations(myList, r=i)))

# Display the Permutations
print("Permutations\n",resList)

输出

Permutations
 [(2,), (3,), (4,), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3), (2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程