我正在使用 itertools 包,并尝试在具有 900 个值的数组中创建 1、2 和 3 的所有可能组合,然后将其转换为 30 x 30 矩阵。我必须执行此操作的代码在下面并且工作正常。
for data in itertools.product([1,2,3], repeat=900):
datalist=list(data)
landarray=np.asarray(datalist).reshape(30, 30)
然而,我想要做的是让每个值(1、2 和 3)在 900 个值数组中恰好出现 300 次。感谢您的帮助!
最佳答案
您想生成 np.repeat([1,2,3], 300)
多重集的所有排列。 There is an algorithm that allows to generate the next permutation in O(1)
.这是一个使用 C++ std::next_permutation()
function 的简单算法并按字典顺序打印排列:
#!/usr/bin/env python
"""Print all multiset permutations."""
import pyximport; pyximport.install() # $ pip install cython
from next_permutation import next_permutation
n = 3
multiset = bytearray('a'*n + 'b'*n + 'c'*n)
print(multiset)
while next_permutation(multiset):
print(multiset)
其中 next_permutation
模块是在 Cython 中定义的 Python 的 C 扩展模块:
# cython: boundscheck=False
#file: next_permutation.pyx
cimport cpython.array # support array.array() on Python 2
from libcpp cimport bool
ctypedef unsigned char dtype_t
ctypedef dtype_t* Iter
cdef extern from "<algorithm>" namespace "std":
bool cpp_next_permutation "std::next_permutation" (Iter first, Iter last)
def next_permutation(dtype_t[:] a not None):
return cpp_next_permutation(&a[0], &a[0] + a.shape[0])
要构建它,请指定语言为 C++:
#file: next_permutation.pyxbld
from distutils.extension import Extension
def make_ext(modname, pyxfilename):
return Extension(name=modname,
sources=[pyxfilename],
language="c++")
输出
aaabbbccc
aaabbcbcc
aaabbccbc
aaabbcccb
aaabcbbcc
aaabcbcbc
aaabcbccb
aaabccbbc
aaabccbcb
aaabcccbb
aaacbbbcc
aaacbbcbc
aaacbbccb
aaacbcbbc
aaacbcbcb
aaacbccbb
..snip..
cccaabbba
cccabaabb
cccababab
cccababba
cccabbaab
cccabbaba
cccabbbaa
cccbaaabb
cccbaabab
cccbaabba
cccbabaab
cccbababa
cccbabbaa
cccbbaaab
cccbbaaba
cccbbabaa
cccbbbaaa
next_permutation()
函数接受任何支持缓冲区接口(interface)的东西,例如,它支持 numpy 数组:
import numpy as np
multiset = np.repeat(np.array([1,2,3], dtype=np.uint8), 3)
关于Python itertools.产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233616/