【Grasshopper】【Python】点集排序:带索引的Z字形排序算法

Grasshopper Python点集排序:带索引的Z字形排序算法

1. 功能介绍

这段代码实现了一个在Grasshopper中的点集排序功能,不仅可以将空间中的点按照Y坐标分组并在每组内按X坐标排序,还能追踪每个点的原始索引位置。

2. 输入输出参数

  • 输入参数:
    • x: 待排序的点集(Point List)
    • t: 容差值(Number),默认2000
  • 输出参数:
    • a: 排序后的点集(Point List)
    • i: 排序后点的原始索引(Number List)

3. 核心算法流程

否 是 输入点集 点集是否为空? 创建点索引对 返回None 按Y坐标分组 组内按X排序 提取排序后的点 提取对应的索引 输出排序点集 输出索引列表

4. 代码解析

4.1 点索引对的创建和处理

python 复制代码
points_with_index = list(enumerate(x))
  • 使用enumerate()创建(索引, 点)对
  • 将每个点与其原始位置绑定

4.2 分组函数

python 复制代码
def groupPointsByY(points_with_index, tolerance):
    points_with_index = sorted(points_with_index, key=lambda pair: pair[1].Y)
    groups = []
    current_group = [points_with_index[0]]
    current_y = points_with_index[0][1].Y
  • 函数接收点索引对和容差值
  • 使用lambda函数访问点的Y坐标进行排序
  • pair[1]访问点对象,pair[0]访问索引

4.3 分组逻辑

python 复制代码
for p in points_with_index[1:]:
    if abs(p[1].Y - current_y) <= tolerance:
        current_group.append(p)
    else:
        groups.append(current_group)
        current_group = [p]
        current_y = p[1].Y
  • 遍历点索引对
  • 基于Y坐标差值分组
  • 保持索引与点的关联

4.4 排序和结果提取

python 复制代码
for group in grouped_points:
    group_sorted = sorted(group, key=lambda pair: pair[1].X)
    for index, point in group_sorted:
        sorted_points.append(point)
        sorted_indices.append(index)
  • 组内按X坐标排序
  • 分别提取点和索引
  • 维护排序后的两个列表

5. Python语法要点

5.1 元组拆包

python 复制代码
for index, point in group_sorted:
  • 直接将元组拆分为两个变量
  • 简化数据访问

5.2 Lambda表达式

python 复制代码
key=lambda pair: pair[1].X
  • 用于定义排序键函数
  • 访问元组中点对象的坐标

5.3 列表操作

python 复制代码
sorted_points.append(point)
sorted_indices.append(index)
  • 使用append()逐个添加元素
  • 维护两个平行列表

6. 数据结构

6.1 点索引对

复制代码
(index, point) 结构:
- index: 原始位置
- point: 点对象
  - X: X坐标
  - Y: Y坐标
  - Z: Z坐标

6.2 分组结构

复制代码
groups = [
    [(index1, point1), (index2, point2), ...],  # 第一组
    [(index3, point3), (index4, point4), ...],  # 第二组
    ...
]
相关推荐
SsummerC44 分钟前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
Tandy12356_1 小时前
Godot开发2D冒险游戏——第一节:主角登场!
python·游戏引擎·godot
西柚小萌新2 小时前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
橘猫云计算机设计2 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
YOULANSHENGMENG2 小时前
linux 下python 调用c++的动态库的方法
c++·python
SsummerC3 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
一眼青苔3 小时前
切割PDF使用python,库PyPDF2
服务器·python·pdf
电商数据girl3 小时前
产品经理对于电商接口的梳理||电商接口文档梳理与接入
大数据·数据库·python·自动化·产品经理
三道杠卷胡4 小时前
【AI News | 20250424】每日AI进展
人工智能·pytorch·python·语言模型·github
T糖锅G5 小时前
小白自学python第二天
python