【问题标题】:python: sort coordinates in csv filepython:对csv文件中的坐标进行排序
【发布时间】:2014-02-07 06:01:45
【问题描述】:

我在 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

我想按以下顺序对坐标进行排序:从西北角开始,然后是东西南角,例如:

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

必须保持高度,并粘在给定的 2D 坐标上。

我尝试了简单的第一列降序和第二列升序,但没有得到想要的顺序。

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')

提前致谢。

【问题讨论】:

    标签: python sorting csv coordinates


    【解决方案1】:

    您也可以一次性完成排序:

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

    【讨论】:

      【解决方案2】:

      你的问题是你假设列表是 1-indexed,而实际上它们不是:

      [55.000000, 14.000000, 34.727]
      #0          1          2
      

      另外,你排序的顺序不对,需要按经度排序然后纬度:

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

      【讨论】:

      • 是的,您对索引是正确的,但这是错误的,在我的原始文件中,我前面还有一列。无论如何,按照您提出的方式对四点摘录进行排序似乎没问题,但在较大的文件中结果错误。
      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 2015-06-14
      • 2017-04-16
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      相关资源
      最近更新 更多