# Python 排列组合的实现

``````考虑这样一个问题，给定一个矩阵（多维数组，<span style="color:#E53333;">numpy.ndarray()</span>），如何<span style="color:#E53333;">shuffle</span>这个矩阵（也就是对其行进行全排列），如何随机地选择其中的k行，这叫组合，实现一种某一维度空间的切片。例如五列中选三列（全部三列的排列数），便从原有的五维空间中降维到三维空间，因为是全部的排列数，故不会漏掉任何一种可能性。
``````

``````<br />
``````
• np.random.permutation()
• itertools.combinations()
• itertools.permutations()
``````<br />
``````
```# 1. 对0-5之间的数进行一次全排列
>>>np.random.permutation(6)
array([3, 1, 5, 4, 0, 2])
# 2. 创建待排矩阵
>>>A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# 3. shuffle矩阵A
>>>p = np.random.permutation(A.shape[0])
>>>p
array([1, 2, 0])
>>>A[p, :]
array([[ 5,  6,  7,  8],
[ 9, 10, 11, 12],
[ 1,  2,  3,  4]])```

### 的实现

``````<br />
``````
```>>>from itertools import combinations
>>>combins = [c for c in  combinations(range(5), 2)]
>>>len(combins)
10
>>>combins               # 而且是按序排列
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

>>>c = [c for c in combinations(range(A.shape[0]), 2)]
>>>A[c[0], :]           # 一种排列
array([[1, 2, 3, 4],
[5, 6, 7, 8]])```
``````<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAlCAYAAAAnQjt6AAAAAXNSR0IArs4c6QAAAARnQU1BAACx jwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAMXSURBVFhH7Zctk6swFIb3H9ZEYVCYKgwKg6pB 1aAw9SgMak0UBoWpqonCoDCo956EFEhKF+gsc6+470ym00CSJzlf4Qv/iP6D2DoYpEGVhvAchtPp BOb6iG4cotOPZzoQpEEReLh8C/Tqf4t7FoAR0MlNUFswH4N0ZawmZUmte0z19FydgpeiHkhIAvmZ QKjfSe+6b9BnIH2NxBkmPL0B6Xg0PD8FKFrdSaoTPS4o6MwmfQQisrNeZJhwts5MHURdoTYcokcZ 63FxqU02aD9IUyB4QmiQ+c5+VFciZnKcg2Syl9JOkI52NETA1Mjx9NM13VNXjXHJnHbg7ALp6wQu TRQkyexUtoF0aiyDT066EL17QAQy6fHnDMIwDznjmm3k+4whLITueNVmkJaigI22pajZCtJwXFwX cTkPnRTetTROZhuIdjIWcR0hBKKcbmhvIljaAwlBJJVpDJF5L/lnE8jgZAHycecya66ByHfIsZkL z/OM5tAmAusY10GaXPmDa2TC1gCxJ5Vqi2B8vtRs+BWQFjySu4pRWq4+ZkhqSyB79SOIDFeHQi7i r7mzTmb55K2TbNcPIHekLi3iRMjKClVltu+rN4FcKz3mc70FaVZsbLQ9af6NlkFajkiGKxWmpSyo RGYbQfz8CJCe1nDIQSMsuMake0r+8zyV5TQv+A1F9UA7q2998wDP6Jam/z/1CkILqHoyJY1lGWme osospkrzyJoag0fObZ+0CaIyIb3spOSqK2rX640CoRqjrofMgRdeUdTLG/xCJ1DLKMhi+GPadnHJ uXWpGdSJWkUNzy/q5J67DOhSrCLqMdlTgWwM7a+OX/Rkr82+V9oZdbFRPXri7wLRv4dIgcQFKjrt UNaZMEZWvTPNgRqclcxcPNQpdY/bULdWnfWX9ch8+NncvM/Lswvb6oeCLKnJfeVLv/Nds1F916Gz 8stYOqzPkMNA5JfekD/MZPdXQOSCzLsZyfGeUvmg/nNuJvnjTCM/S+Wlmc/CVRSI6FOVBTmEZbKD nVWAX8PZfTXEtagXK/XBINv1j4AAfwBhF+gpJd55bAAAAABJRU5ErkJggg==" <="" p=""><span style="font-size:18px;"><strong>的实现</strong></span>

<br />
``````
```>>>from itertools import permutations
>>>pertumations(range(5), 2)

>>>perms = permutations(range(5), 2)
>>>perms
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1),
(2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3)]
>>>len(perms)
20```
``````注意combinations和<a href="https://www.361way.com/python-itertools/5705.html" target="_blank" rel="noopener">product</a>（笛卡尔积）的区别，后者一般传入的是两个数组，而前者是通过顺序排列，且传入的是排除字符的长度位参数。

<br />
``````