如何基于匹配点号将属性插入测量点列表指定位置?
如何用Python实现测量点属性匹配插入?
原始测量点列表和属性列表如下:
survey_points = [ [101,123.456,101.234,99.234] , [102,88.243,211.245,100.834] , [103,13.556,134.234,99.234] , [104,12.345,95.342,99.121] ] survey_points_attributes = [ [101,305] , [102,306] , [103,305] , [104,308] , [105,310] , [106,307] , [107,306] , [108,305] , [109,305] , [110,307] ]
其中:
survey_points每个子列表格式为:点号、距离、水平角、垂直角survey_points_attributes每个子列表格式为:点号、属性/代码
需求:以点号为匹配关键字,将对应属性插入到survey_points每个子列表的点号与距离之间,最终输出如下:
survey_points = [ [101,305,123.456,101.234,99.234] , [102,306,88.243,211.245,100.834] , [103,305,13.556,134.234,99.234] , [104,308,12.345,95.342,99.121] ]
实现方法
步骤1:将属性列表转为字典(优化匹配效率)
把survey_points_attributes转换成以点号为键、属性为值的字典,这样单次查找属性的时间复杂度为O(1),比反复遍历列表更高效。
步骤2:遍历测量点列表插入属性
遍历survey_points中的每个子列表,根据点号从字典中取出对应属性,插入到点号之后的位置。
完整代码如下:
# 原始数据 survey_points = [ [101,123.456,101.234,99.234] , [102,88.243,211.245,100.834] , [103,13.556,134.234,99.234] , [104,12.345,95.342,99.121] ] survey_points_attributes = [ [101,305] , [102,306] , [103,305] , [104,308] , [105,310] , [106,307] , [107,306] , [108,305] , [109,305] , [110,307] ] # 转换属性列表为字典 attr_dict = {point[0]: point[1] for point in survey_points_attributes} # 遍历插入属性 for point in survey_points: point_num = point[0] # 检查点号是否存在于属性字典中,避免报错 if point_num in attr_dict: # 在索引1的位置(点号之后)插入属性 point.insert(1, attr_dict[point_num]) # 输出结果 print("survey_points =", survey_points)
代码说明
- 用字典推导式快速构建属性映射,数据量越大,效率优势越明显;
- 利用列表
insert()方法精准插入属性到指定位置; - 增加存在性检查,防止
survey_points中出现属性列表未收录的点号导致程序报错。
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

