我有一个像这样的对象数组 [{'x': -50, 'y': 30}, {'x': 70, 'y': -68} ...] 最大范围是 -200| +200。
我需要找到一些坐标范围内的所有坐标。假设我添加了坐标 50|50 和范围 20,所以最大 x 是 70 低 30,最大 y 70 和低 y 30。
所以它应该找到该范围内的所有坐标并返回一个新的对象列表。
我试过这个和它对 x 坐标的工作,但对 y 来说并不多。
谢谢你的帮助。
def find_coords(self, x, y, z):
with open('allcoords.json') as json_file:
data = json.load(json_file)
xcoords = []
for s in data:
if s['x'] > (int(x) + int(z)):
break
if s['x'] > (int(x) - int(z)):
xcoords.append(s)
ycoords = []
for ys in xcoords:
if ys['y'] > (int(y) + int(z)):
break
if ys['y'] > (int(y) - int(z)):
ycoords.append(ys)
您正在迭代存储在您的allcords.json
. 代码本身没问题,但是对于 Y 坐标,您引用了错误的源数据。Y 线也在 中data
,但您正在迭代ycoords
,这是一个空数组,没有任何意义。
def find_coords(self, x, y, z):
with open('allcoords.json') as json_file:
data = json.load(json_file)
xcoords = []
for s in data:
if s['x'] > (int(x) + int(z)):
break
if s['x'] > (int(x) - int(z)):
xcoords.append(s)
ycoords = []
for ys in data:
if ys['y'] > (int(y) + int(z)):
break
if ys['y'] > (int(y) - int(z)):
ycoords.append(ys)
另外,我认为这段代码有点太复杂了。您可以使用 filter 方法重写如下内容并使其更具可读性:
def find_coords(self, x, y, z):
with open('allcoords.json') as json_file:
data = json.load(json_file)
xcoords = list(filter(lambda s: int(x) - int(z) < s['x'] < int(x) + int(z), data))
ycoords = list(filter(lambda s: int(y) - int(z) < s['y'] < int(y) + int(z), data))
编辑:基于评论中的讨论。
抱歉,我误解了您想要的内容。我想最后你可能只需要以下内容:
def find_coords(self, x, y, z):
with open('allcoords.json') as json_file:
data = json.load(json_file)
coords = list(
filter(
lambda s: (
int(x) - int(z) < s['x'] < int(x) + int(z)
and int(y) - int(z) < s['y'] < int(y) + int(z)
data)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句