gpt4 book ai didi

Python:一种更 Pythonic 的方式来遍历网格分类

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:02 25 4
gpt4 key购买 nike

我有一个 11×11 大小的网格,它放置在散点图上。散点图包含 100 个随机生成的对。在每个网格空间内,是一个分类类型,其中:

类型 A 大于 0,但在 X 和 Y 轴上都小于 0.5,B 型大于 0.5,但 X 和 Y 轴均小于 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, 10.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()

最佳答案

您可以将 Type 设为矩阵并四舍五入值以找到您的索引:

from random import random

# An 11 x 11 matrix of lists
Type = 11 * (11 * ([],),)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(np.arange(0.5, 10.5, 1))
ax.set_yticks(np.arange(0.5, 10.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 implies
for x in Type:
for y in x:
print y, len(y)

# Print only buckets with both values in the same range as your question implies
for x in range(11):
print Type[x][x], len(Type[x][x])

plt.grid()
plt.show()

关于Python:一种更 Pythonic 的方式来遍历网格分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com