在 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)]
广告