如何使用Numpy打印给定区间内的数组元素?
在这个程序中,我们需要打印numpy数组中给定区间内的元素。所使用的不同numpy函数是numpy.where()和numpy.logical_and()。
阅读更多:Python 教程
算法
步骤1:定义一个numpy数组。
步骤2:使用np.where()和np.logical_and()来查找给定范围内的数字。
步骤3:打印结果。
示例代码
import numpy as np
arr = np.array([1,3,5,7,10,2,4,6,8,10,36])
print("原始数组:\n",arr)
result = np.where(np.logical_and(arr>=4, arr<=20))
print(result)
输出
原始数组:
[ 1 3 5 7 10 2 4 6 8 10 36]
(array([2, 3, 4, 6, 7, 8, 9], dtype=int64),)
说明
结果给出了在np.where()函数中满足条件的元素的索引位置。