如何使用Python按照首字段标识对文本文件内的坐标数据进行排序
解决方法
你当前把每条记录的四个属性拆成独立列表的写法,排序时很容易出现属性对应错乱的问题,建议先把每条坐标存为关联的元组,再自定义排序规则即可,同时注意不要用sorted作为自定义变量名,会覆盖Python内置的排序函数。
完整可运行代码如下:
import re # 如果首字段前缀不固定才需要导入,前缀都是p可以省略 records = [] with open("coordinates.txt", "r") as file: for line in file: line = line.strip() # 跳过空行避免报错 if not line: continue data = line.split(";") pid = data[0] east = round(float(data[1]), 2) north = round(float(data[2]), 2) height = round(float(data[3]), 2) records.append((pid, east, north, height)) # 排序逻辑:提取首字段的数字按数值大小排序,避免字符串排序时p10排在p2前面的错误 # 前缀固定是p可以用下面这行 sorted_records = sorted(records, key=lambda x: int(x[0].strip('p'))) # 前缀不固定的话换成下面这行用正则提取数字 # sorted_records = sorted(records, key=lambda x: int(re.search(r'\d+', x[0]).group())) # 如果需要拆分回四个独立列表可以保留下面的代码 id_list = [item[0] for item in sorted_records] east_list = [item[1] for item in sorted_records] north_list = [item[2] for item in sorted_records] height_list = [item[3] for item in sorted_records] print(id_list) print(east_list) print(north_list) print(height_list)
用你提供的样例数据运行后,输出的ID列表为['p1', 'p6', 'p10'],符合预期排序结果。
内容的提问来源于stack exchange,提问作者Code With Faraz
相关产品推荐
相关产品推荐

