Python 排列组合的实现
考虑这样一个问题,给定一个矩阵(多维数组,numpy.ndarray()),如何shuffle这个矩阵(也就是对其行进行全排列),如何随机地选择其中的k行,这叫组合,实现一种某一维度空间的切片。例如五列中选三列(全部三列的排列数),便从原有的五维空间中降维到三维空间,因为是全部的排列数,故不会漏掉任何一种可能性。
涉及的函数主要有:
- np.random.permutation()
- itertools.combinations()
- itertools.permutations()
1# 1. 对0-5之间的数进行一次全排列
2>>>np.random.permutation(6)
3array([3, 1, 5, 4, 0, 2])
4# 2. 创建待排矩阵
5>>>A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
6# 3. shuffle矩阵A
7>>>p = np.random.permutation(A.shape[0])
8>>>p
9array([1, 2, 0])
10>>>A[p, :]
11array([[ 5, 6, 7, 8],
12 [ 9, 10, 11, 12],
13 [ 1, 2, 3, 4]])
combinations实现
1>>>from itertools import combinations
2>>>combins = [c for c in combinations(range(5), 2)]
3>>>len(combins)
410
5>>>combins # 而且是按序排列
6[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
7任取其中的k(k=2)行
8>>>c = [c for c in combinations(range(A.shape[0]), 2)]
9>>>A[c[0], :] # 一种排列
10array([[1, 2, 3, 4],
11 [5, 6, 7, 8]])
permutations的实现
1>>>from itertools import permutations
2>>>pertumations(range(5), 2)
3<itertools.permutations at="" object="">
4>>>perms = permutations(range(5), 2)
5>>>perms
6[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1),
7 (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3)]
8>>>len(perms)
920</itertools.permutations>
注意combinations和product(笛卡尔积)的区别,后者一般传入的是两个数组,而前者是通过顺序排列,且传入的是排除字符的长度位参数。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/ndarray/5786.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.