通过带有np.where函数的数组添加Numpy Python [英] Adding through an array with np.where function Numpy Python
问题描述
我正在尝试编写一个函数,它一次添加一个 Sequence
,直到达到 Number
.因此,由于 Sequence
数组的总和为21,而不是45,因此会将 Sequence
3的第一个元素添加到 Sequence
变成 [3,7,11,3]
.由于 [3、7、11、3]
等于24且小于45,因此要在Sequence中添加下一个元素,即7,因此 Sequence
会更新为 [3、7、11、3、7]
,依此类推,直到 Number>np.sum([Sequence]
is is not return True
.下面的 np.where
函数有问题,我该如何解决?
I am trying to write a function where it adds the Sequence
one at a time until the Number
is reached. So since the the sum of the Sequence
array is 21 and not 45 it will add the first element of the Sequence
3 to the Sequence
so it becomes [3, 7, 11, 3]
. Since [3, 7, 11, 3]
is equal to 24 and is lower than 45 the next element in the Sequence is going to be added which is 7, the Sequence
is updated to be [3, 7, 11, 3, 7]
and so on until Number> np.sum([Sequence]
is does not return True
. The np.where
function below is faulty how can I fix it?
代码:
Number = 45
Number2= 46
Sequence = np.array([3, 7, 11])
p = 0
np.where(Number> np.sum([Sequence]),np.append(Sequence,Sequence[p], p+= 1))
np.where(Number2> np.sum([Sequence]),np.append(Sequence,Sequence[p], p+= 1))
预期产量
Number = [3,7,11,3,7,11,3]
Number2 = [3,7,11,3,7,11,3,7]
推荐答案
我不认为这可以作为一个整体来完成. np.where
的第二个和第三个参数应该是序列.作为循环很简单:
I'm not convinced this can be done as a one-liner. The second and third parameters to np.where
are supposed to be sequences. It's easy as a loop:
seq45 = []
for n in itertools.cycle(Sequence):
seq45.append(n)
if sum(seq45) >= 45: break
这篇关于通过带有np.where函数的数组添加Numpy Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!