Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中按浮点值进行二维数组切片_Python_Arrays_Python 3.x_Numpy_Slice - Fatal编程技术网

Python中按浮点值进行二维数组切片

Python中按浮点值进行二维数组切片,python,arrays,python-3.x,numpy,slice,Python,Arrays,Python 3.x,Numpy,Slice,我想用Python3.x中的x值对[x,y]坐标对数组进行切片,方法类似于问题的解决方案,但使用坐标而不是1d列表 例如,对于坐标的(numpy)数组,我需要如下函数: coords = np.array([[1.5,10],[2.5,20],[3.5,30],[4.5,40],[5.5,50]]) def slice_coords_by_x(xmin, xmax, arr): *some function* slice_coords_by_x(2, 4, arr) >>&g

我想用Python3.x中的x值对[x,y]坐标对数组进行切片,方法类似于问题的解决方案,但使用坐标而不是1d列表

例如,对于坐标的(numpy)数组,我需要如下函数:

coords = np.array([[1.5,10],[2.5,20],[3.5,30],[4.5,40],[5.5,50]])
def slice_coords_by_x(xmin, xmax, arr):
    *some function*
slice_coords_by_x(2, 4, arr)
>>>[[2.5,20],[3.5,30]]

如果解决方案包含或不包含xmin和xmax,则不要过分挑剔,因为我将在1000多个左右的大范围内使用它。

切片并创建具有此类最小-最大限制的掩码,然后选择具有-


如果没有
numpy
,您可以使用
bisect
来查找插入点。请注意,该参数是一个列表(我添加了
None
作为第二个参数,如中所示,但它没有用处)

结果:

[[2.5, 20], [3.5, 30]]
bisect
要求对列表进行排序(似乎是这样),否则将不起作用。

无序 如果给定的点列表无序,则可以使用
过滤器
,并使用
列表
具体化:

def slice_coords_by_x(xmin,xmax,arr):
    return list(filter(lambda p: xmin < p[0] < xmax,arr))
不应该只是

def slice_coords_by_x(xmin, xmax, arr):
    return [i for i in arr if xmin <= i[0] and i[0] <= xmax]
def slice_coords_by_x(xmin,xmax,arr):

返回[i for i in arr如果xmin,那么您基本上想要过滤?是否保证
x
坐标是有序的?您不能简单地使用
[lower]
而不是
[lower,None]
?至少对于
左对分
?否:
类型错误:无序类型:list()
[lower]
仍然是一个
列表
。如果我查询
对分。左对分(arr,[2.5,None])
,我得到
类型错误:无序类型:int()
…使用上面定义的
arr
。很有趣。因此我链接到告诉put
None
的答案是错误的。等等:它必须是python 2,因为你可以将字符串与int等进行比较。在python 3中不再是了。
如果xmin
如果xmin可能,但后者更“pythonic”另外,我也不确定,威廉的答案是否比我的好。那么,为什么我不写一个更容易阅读和理解的方式呢?附言:我在威廉之前写了答案,我实际上在之前把它作为评论输入,删除了它,重新格式化并保存了它,我以前没有看到威廉的答案。回答时你必须更加积极;)注意感谢所有的答案-选择这一个纯粹是因为它不依赖于其他包,并且它保留了numpy数组类型而不是Python自己的数组
[[2.5, 20], [3.5, 30]]
def slice_coords_by_x(xmin,xmax,arr):
    return list(filter(lambda p: xmin < p[0] < xmax,arr))
def slice_coords_by_x(xmin,xmax,arr):
    left = bisect.bisect_left(arr,[xmin])
    right = bisect.bisect_right(arr,[xmax])
    return arr[left:right]
def slice_coords_by_x(xmin, xmax, arr):
    return [i for i in arr if xmin <= i[0] and i[0] <= xmax]