类型A在X和Y轴上都大于0,但小于0.5,
B型在X轴和Y轴上都大于0.5,但小于1.5
等…
我想知道每个网格空间中有多少个点,以及该网格空间中存在的对.这部分不是问题,我只是想知道是否有更多的pythonic方式来编写我的循环,因为我不想为每个网格空间编写if语句.
我的脚本如下:
TypeA = [] TypeB = [] fig = plt.figure() ax = fig.gca() ax.set_xticks(np.arange(0.5,10.5,1)) ax.set_yticks(np.arange(0.5,1)) for ii in range(100): RNumX = randint(0,10) RNumY = randint(0,10) print RNumX,RNumY hold(True) plot1 = plt.scatter(RNumX,RNumY) if RNumX >= 0 and RNumX < 0.5: if RNumY >= 0 and RNumY < 0.5: PairA = (RNumX,RNumY) TypeA.append(PairA) elif RNumY >= 0.5 and RNumY < 1.5: PairB = (RNumX,RNumY) TypeB.append(PairB) SumA = len(TypeA) SumB = len(TypeB) print TypeA,SumA print TypeB,SumB plt.grID() plt.show()解决方法 您可以键入矩阵并对值进行舍入以查找索引:
from random import random# An 11 x 11 matrix of ListsType = 11 * (11 * ([],),)fig = plt.figure()ax = fig.gca()ax.set_xticks(np.arange(0.5,1))ax.set_yticks(np.arange(0.5,1))for ii in range(100): # If you want to use floats in stead of ints RNumX = 0.5 + 10 * random() RNumY = 0.5 + 10 * random() print RNumX,RNumY hold(True) plot1 = plt.scatter(RNumX,RNumY) # Round the coordinates to find the indices Type[int(RNumX + 0.5)][int(RNumY + 0.5)].append((RNumX,RNumY))# Print all buckets as your snippet implIEsfor x in Type: for y in x: print y,len(y)# Print only buckets with both values in the same range as your question implIEsfor x in range(11): print Type[x][x],len(Type[x][x])plt.grID()plt.show()总结
以上是内存溢出为你收集整理的Python:循环网格分类的更多Pythonic方法全部内容,希望文章能够帮你解决Python:循环网格分类的更多Pythonic方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)