Python中如何通过一次循环按第二维度拆分二维数组?
实现方案
方案1:Python原生循环实现(无numpy依赖)
如果是普通Python列表存储的点数据,直接遍历一次做判断分类即可,逻辑和你原有写法完全对齐:
points_right = [] points_left = [] threshold = p0[0] for point in points: if point[0] > threshold: points_right.append(point) elif point[0] < threshold: points_left.append(point) # 等于阈值的点会被自动忽略,和你原有筛选逻辑保持一致
方案2:numpy场景下的单遍历实现
如果你用的是numpy数组,也可以通过单次遍历完成拆分,避免两次布尔索引带来的两次遍历开销:
import numpy as np threshold = p0[0] # 预先分配数组避免动态append的性能损耗,容量上限为原数组长度 points_right = np.empty_like(points) points_left = np.empty_like(points) # 记录两个数组的有效元素个数 r_cnt = 0 l_cnt = 0 for point in points: if point[0] > threshold: points_right[r_cnt] = point r_cnt += 1 elif point[0] < threshold: points_left[l_cnt] = point l_cnt += 1 # 截断到实际有效长度 points_right = points_right[:r_cnt] points_left = points_left[:l_cnt]
如果你需要保留
point[0] == p0[0]的点,自行调整判断分支,将这部分点加到任意一侧或者单独存为第三个数组即可。
内容的提问来源于stack exchange,提问作者prof_FL
相关产品推荐
相关产品推荐

