如何对NumPy数组按y、x坐标排序并对同类型元素分组?
实现方案
核心逻辑
- 先对数组元素排序:优先按y坐标升序排列,y值相等时按x坐标升序排列,注意排序时要将坐标从字符串转为整数避免字典序排序错误
- 再按元素类型分配group_id:相同元素类型对应同一个group_id,新类型按出现顺序分配自增id
完整代码
import numpy s = numpy.array([ #element type, x,y,width,height ["hyperlink", 5, 150, 25, 10], ["paragraph", 20, 60, 10, 10], ["image", 85, 150, 25, 10], ["radio", 20, 60, 10, 10], ["radio", 85, 150, 25, 10], ["button", 20, 60, 10, 10], ["text_field", 20, 40, 25, 10], ["label", 10, 10, 20, 10]]) # 第一步:按y升序、y相同按x升序排序 sorted_items = sorted(s.tolist(), key=lambda item: (int(item[2]), int(item[1]))) # 第二步:按元素类型分配group_id type_id_map = {} current_group_id = 1 result = [] for item in sorted_items: elem_type, x, y, width, height = item # 新类型分配新id if elem_type not in type_id_map: type_id_map[elem_type] = str(current_group_id) current_group_id += 1 # 组装结果字典 result.append({ "element_type ": elem_type, "group_id": type_id_map[elem_type], "x": x, "y": y, "width": width, "height": height }) # 打印输出 for item in result: print(item)
运行输出
{'element_type ': 'label', 'group_id': '1', 'x': '10', 'y': '10', 'width': '20', 'height': '10'} {'element_type ': 'text_field', 'group_id': '2', 'x': '20', 'y': '40', 'width': '25', 'height': '10'} {'element_type ': 'paragraph', 'group_id': '3', 'x': '20', 'y': '60', 'width': '10', 'height': '10'} {'element_type ': 'radio', 'group_id': '4', 'x': '20', 'y': '60', 'width': '10', 'height': '10'} {'element_type ': 'button', 'group_id': '5', 'x': '20', 'y': '60', 'width': '10', 'height': '10'} {'element_type ': 'hyperlink', 'group_id': '6', 'x': '5', 'y': '150', 'width': '25', 'height': '10'} {'element_type ': 'image', 'group_id': '7', 'x': '85', 'y': '150', 'width': '25', 'height': '10'} {'element_type ': 'radio', 'group_id': '4', 'x': '85', 'y': '150', 'width': '25', 'height': '10'}
注:你给出的期望输出中label和text_field的group_id相同属于笔误,按需求同类型元素才会分配相同group_id,若你有其他分组规则,修改
type_id_map的赋值逻辑即可。
内容的提问来源于stack exchange,提问作者Nadeeshani Welgama
相关产品推荐
相关产品推荐

