在对象数组中查找坐标

缺口

我有一个像这样的对象数组 [{'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)
losik123

您正在迭代存储在您的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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在对象数组中查找数据数组

来自分类Dev

在对象数组的数组中查找交集

来自分类Dev

在对象中查找数组元素

来自分类Dev

ReactJS / JavaScript在对象中查找数组

来自分类Dev

在对象的JavaScript数组中查找属性

来自分类Dev

MongoDB在对象数组中查找

来自分类Dev

在对象数组中查找特定属性

来自分类Dev

在对象中查找数组值

来自分类Dev

在对象数组中查找数组中的元素

来自分类Dev

在对象的嵌套数组中查找父对象。如何?

来自分类Dev

在对象的父数组中查找唯一的对象

来自分类Dev

在对象数组中查找对象的索引

来自分类Dev

创建查询以在对象数组中查找对象

来自分类Dev

查找数组中是否存在对象中的值

来自分类Dev

通过使用数组中的值在对象中查找键

来自分类Dev

如何在对象数组中查找值

来自分类Dev

在对象数组中查找属性的最大值

来自分类Dev

在对象数组中查找所有键

来自分类Dev

在对象数组中查找所有键

来自分类Dev

使用 nodejs 在对象数组中查找特定键值

来自分类Dev

在对象数组中查找重复元素

来自分类Dev

Mongoose 查询在对象数组中查找特定元素

来自分类Dev

通过 ReactJs 在对象数组中查找最大值

来自分类Dev

如何通过嵌套在对象数组的属性中的对象属性的值在对象数组中查找多个索引?

来自分类Dev

在对象数组内部查找对象

来自分类Dev

根据坐标在数组中查找对象

来自分类Dev

在对象的2D数组中打印坐标标记。爪哇

来自分类Dev

在对象ID数组中查找对象ID使用Mongoose返回空数组

来自分类Dev

FirstIndex:of: 在对象数组中