gpt4 book ai didi

Python Numpy : All combinations from array or scalar

转载 作者:行者123 更新时间:2023-12-01 04:36:28 26 4
gpt4 key购买 nike

我需要从数组(或标量)中获得所有可能的组合。

我有一个数组 np.array([0, 1, 0, 1]) 或标量 np.sum(np.array([0, 1, 0, 1 ]))。现在我需要所有组合,例如:

[[2,0,0,0],
[1,1,0,0],
[1,0,1,0],

[0,0,1,1],
[0,0,0,2]]

所有可能组合的元素的总和不能超过标量的总和。我从“Using numpy to build an array of all combinations of two arrays”中知道了解决方案。但这对我解决这个问题没有帮助。有人有什么想法吗?

最佳答案

这是一种非常简单(且效率低下)的方法,可以针对标量情况执行您想要的操作。对于数组情况,只需从数组的总和和长度中获取数字 n 和 m。我确信通过一些额外的思考,可以做得比这更好,但除非你的数字变得明显更大,否则这就足够了:

import itertools
import numpy as np

n=2 #number of elements to distribute
m=4 #length of arrays to distribute in
arrays = []
for combination in itertools.combinations_with_replacement(range(m), n):
arrays.append(np.zeros(m,dtype=int))
for index in combination:
arrays[-1][index] += 1

for array in arrays:
print(array)

输出:

[2 0 0 0]
[1 1 0 0]
[1 0 1 0]
[1 0 0 1]
[0 2 0 0]
[0 1 1 0]
[0 1 0 1]
[0 0 2 0]
[0 0 1 1]
[0 0 0 2]

关于Python Numpy : All combinations from array or scalar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31609681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com