Arash Howaida
Arash Howaida

Reputation: 2617

Python sort partial list items

I have parsed a tsv file and have this structure:

[['x1','y1','x2','y2'],
[1,1,0,80],
[.95,1,.05,70],
[.93,1,.1,65],
…
]

My x1 values are in descending order; starting from 1 going down to 0. My x2 values are in ascending order; starting from 0 going up to 1. I need both to be in ascending order. I can't just flip the list or else x2 will be in descending order. Also, note that x1 and y1 are pairs, so whatever we do to x1 we must do to y1 to make sure the data is still preserved.

I have omitted my attempt out of shame, but if everyone promises not to laugh, what I tried was adding a -i to get the nth last item from my original list. raw_data is the data structure seen above.

new_list = [[raw_data[2][-i], raw_data[3][-i]] for i in raw_data

Unfortunately, that did not work.

Question: How can I write a list comprehension such that my x1 (and the corresponding y1 values) are in ascending order?

Upvotes: 0

Views: 318

Answers (1)

Frerich Raabe
Frerich Raabe

Reputation: 94409

You can take advantage of the fact that when comparing tuples, the comparison is based on the first element -- and for equal first elements, the second element is compared. With that in mind, you could first massage your list of lists into a list of tuples associating each 'x1' value with the respective 'y1' value, and then getting the sorted list:

>>> lst = [['x1','y1','x2','y2'],[1,1,0,80],[.95,1,.05,70],[.93,1,.1,65]]
>>> sorted((x1, y1) for x1, y1, x2, y2 in lst[1:])
[(0.93, 1), (0.95, 1), (1, 1)]

Upvotes: 2

Related Questions