我正在尝试在 Python 中创建从第 n 个数组创建数组的方法。我看过 Numpy 但该方法似乎不适合我的要求。 以下是我的 JavaScript 代码。 numArr = [[1],[12],[22],[31,32,33],[41,42]] ,结果将是 [1,12,22,31,41],[1,12,22,31,42],[1,12,22,32,41],[1,12,22,32,42],[1 ,12,22,33,41],[1,12,22,33,42]
for (var i = 0; i < numArr.length; i++) {
tempNumArr = new Array(totalNumArr.length * numArr[i].length);
for (var j = 0; j < totalNumArr.length; j++) {
for (var k = 0; k < numArr[i].length; k++) {
tempNumArr[j * numArr[i].length + k] = new Array();
if (i !== 0)
tempNumArr[j * numArr[i].length + k] = totalNumArr[j].slice();
tempNumArr[j * numArr[i].length + k].push(numArr[i][k]);
}
}
totalNumArr = tempNumArr;
}
所以基本上我们需要连接 N 个数组并返回连接数组 N 次。
arr = np.concatenate(numArr)
arr = arr * len(numArr)
你要找的是数组的乘积
import itertools
ls = [[1],[12],[22],[31,32,33],[41,42]]
print([p for p in itertools.product(*ls)])