如何在if语句的条件部分使用数组?我希望程序检查每个元素的绝对值,并返回相应的部分。这给了一些希望:Function of Numpy Array with if-statement
但这种技术在我的情况下是行不通的。
这是我正在尝试的代码:def v(x,y):
if x[abs(x)
return #something 1
if x[a
return #something 2
if x[b
return #something 3
这里,x和y是数组。(实际上是由x,y = ogrid[-R:R:.01, -R:R:.01]创建的网格)
编辑:我发现的最好的方法(经过多次尝试和错误)是使用布尔数组。代码如下:#Create a grid of coordinates. XY-Plane.
x,y=ogrid[-R:R+1:1,-R:R+1:1]
#Create the polar distance 2D array. Conditions are tested on this array.
r=sqrt(x**2+y**2)
#Create 2D array to hold the result
v=zeros([len(x*y),len(x*y)],float)
#idr is the boolean 2D array of same size and shape as r.
#It holds truth values wherever the condition is true.
idr=(r