a = np.array([10,20,30,40])
threshold = 30
# To get the first value that
# matches the condition
matched_value = a[a.cumsum() > threshold][0]
print(f'matched_value: {matched_value}')
# To get the first index that
# matches the condition
matched_index = np.where(a.cumsum() > threshold)[0][0]
print(f'matched_index: {matched_index}')
输出:
matched_value: 30
matched_index: 2
范例
这是另一个例子
import numpy as np
#a = np.random.randint(0, high=100, size=10)
a = [75, 38, 23, 59, 0, 16, 96, 60, 52, 58]
a = np.array(a)
print(f'array: {a}')
# Cumulative sum
print(f'cumsum: {a.cumsum()}')
# First element in the array where the
# cumulative sum is greater than a given value
threshold = 180
value = a[a.cumsum() > threshold][0]
print(f'Target Cumsum Threshold: {threshold} \n' + f'Value: {value}')
import numpy as np
a= np.array([10,20,30,40])
threshold = 30
a = list(a)
indices_list = [a.index(item) for i,item in enumerate(a) if sum(a[:i+1])>=threshold]
if indices_list !=[]:
print('Required element is',a[indices_list[0]])
解决方案
您可以在一行中使用
a[a.cumsum() > threshold][0]
用于匹配的value
np.where(a.cumsum() > threshold)[0][0]
用于匹配的index
具体如下
输出:
范例
这是另一个例子
输出:
假设a是一个numpy数组[10,20,30,40],阈值为30。 返回索引的代码,从该索引中,累积和大于或等于阈值
相关问题 更多 >
编程相关推荐