【发布时间】:2018-08-30 15:02:58
【问题描述】:
我有两个类似的 numpy 数组,它们代表坐标:
import numpy as np
x=np.array([1,3,2,4,6,5,4,1])
y=np.array([4,4,3,2,2,1,3,5])
我也有n方块:
s1 -> x=0 to 3, y=0 to 3
s2 -> x=3 to 6, y=3 to 6
s3 -> ...
s4 -> ...
我想计算每个正方形内的点数。这归结为评估n 不等式。
我的方法很冗长并且(可能)效率低下:
count1=0
count2=0
count3=0
count4=0
for j in range(0, len(x)):
#Square 1
if x[j]<=3 and y[j]<=3:
count1+=1
#Square 2
if x[j]<=3 and y[j]>3 and y[j]<=6:
count2+=1
#Square 3
if x[j]>3 and x[j]<=6 and y[j]<=3:
count3+=1
#Square 4
if x[j]>3 and x[j]<=6 and y[j]>3 and y[j]<=6:
count4+=1
给定我的两个数组,返回:
In[1]: count1, count2, count3, count4
Out[1]: (1, 3, 4, 0)
我真正的问题包括可变数量的方格(可能是 6 个,也可能是 36 个,等等)。
有没有一种方法可以自动生成count 变量以及if 语句的数量和边界?
【问题讨论】:
-
你不能把方块的边界放在一个循环中吗?
标签: python numpy for-loop if-statement inequalities