简体   繁体   English

python:在csv文件中排序坐标

[英]python: sort coordinates in csv file

I have set of three dimensional coordinates in csv file, like: [two first columns are respectively latitude and longitude in decimal degrees, third one is elevation] 我在csv文件中设置了三维坐标​​,如:[两个第一列分别是十进制度数的纬度和经度,第三列是高程]

49.000000,14.000000,47.206
55.000000,14.000000,34.727
49.000000,24.366667,31.979
55.000000,24.366667,24.744

I would like to sort the coordinates in the following order: starting from north-west corner then go east-south, like: 我想按以下顺序对坐标进行排序:从西北角开始然后向东南走,如:

55.000000,14.000000,34.727
55.000000,24.366667,24.744
49.000000,14.000000,47.206
49.000000,24.366667,31.979

Elevation has to be kept, glued to given 2D coordinates. 必须保持高度,粘合到给定的2D坐标。

I tried simple descending 1st column and ascending 2nd column but got no desired order. 我尝试了简单的下降第1列和上升第2列,但没有得到所需的顺序。

import csv

coordinates = [];

file_in = csv.reader(open('NewFile.csv', 'rb'), delimiter=',', quotechar='|');
file_out = '11dataout.txt'
fout=open(file_out,"w")

for row in file_in:
    coordinates.append(row)
coordinates.sort(key=lambda x: x[1], reverse=True)                              
coordinates.sort(key=lambda x: x[2])
fout.write(str(coordinates))
fout.write('\n')

Thanks in advance. 提前致谢。

您也可以一次性进行排序:

coordinates.sort(key = lambda x: (-x[0], x[1]))

You problem is that you assume lists are 1-indexed, when they aren't: 你的问题是你假设列表是1索引的,当它们不是:

[55.000000, 14.000000, 34.727]
#0          1          2

Also, you sort in the wrong order, you need to sort by longitude then latitude: 此外,您按错误的顺序排序,您需要按经度排序然后纬度:

coordinates.sort(key=lambda x: x[1])                              
coordinates.sort(key=lambda x: x[0], reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM