Sorting X,Y,Z data

This is the place for queries that don't fit in any of the other categories.

Sorting X,Y,Z data

Postby jeroen1225 » Wed Nov 06, 2013 3:09 pm

Hi,

I am trying to find a way to sort data I read from a large file containing X,Y,Z data. The file could look like:

234213.45,45324.56,5.67
234223.46,45124.56,5.77
234215.87,45332.87,3.56
234265.45,45345.86,1.67
...

I would like to order on the first column first and then on the second and then write it to a temporary file for further use.

Can anyone get me some help as I am stuck.

Thanks!
jeroen1225
 
Posts: 4
Joined: Wed Nov 06, 2013 3:02 pm

Re: Sorting X,Y,Z data

Postby stranac » Wed Nov 06, 2013 3:57 pm

Ok, you can use the sorted() built-in to do this.
If you're having trouble doing it, post some code.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1093
Joined: Thu Feb 07, 2013 3:42 pm

Re: Sorting X,Y,Z data

Postby jeroen1225 » Thu Nov 07, 2013 9:38 am

This is what I have so far:

Code: Select all
import csv

coordinates = [];

file_in = csv.reader(open('c:/testdata/ascii.xyz', 'rb'), delimiter=',', quotechar='|');
file_out = 'c:/testdata/dataout.txt'
fout=open(file_out,"w")

for row in file_in:
    coordinaten.append(row)
coordinaten.sort(key=lambda x: x[0])                              #sort on X ascending
coordinaten.sort(key=lambda x: x[1], reverse=True)                #sort on Y descending
fout.write(coordinates)
fout.write('\n')
jeroen1225
 
Posts: 4
Joined: Wed Nov 06, 2013 3:02 pm

Re: Sorting X,Y,Z data

Postby stranac » Thu Nov 07, 2013 10:24 am

Read this to learn how to use code tags.

You probably want something like:
Code: Select all
coordinates.sort(key=lambda row: (float(row[0]), -float(row[1])))

But it might be better(more readable), if you use a normal function instead of the lambda.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1093
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: rlrhk and 3 guests