0

I have a program where I want to sort by an x coordinate.

My list looks like this:

[('Name1', (449, 923, 634, 737)), ('Name2', (390, 1356, 613, 1133)), ('Name3', (1062, 1749, 1216, 1594))] 

Each element of the original list has a name, and then a set of x1, y1, x2, y2 coordinates. If I want to sort my list by the x2 coordinate, how would I do that?

I've searched around and found that you can use "itemgetter" to do something like this:

preds = sorted(preds, key=itemgetter(1))

But that is getting the whole set of coordinates. How would I sort by say, the third coordinate, specifically?

Xrae
  • 3
  • 2

1 Answers1

-1

You can sort it with key=lambda t:t[1][2]

>>> preds = [('Name1', (449, 923, 634, 737)), ('Name2', (390, 1356, 613, 1133)), ('Name3', (1062, 1749, 1216, 1594))] 
>>> preds.sort(key=lambda t: t[1][2])
>>> preds
[('Name2', (390, 1356, 613, 1133)), ('Name1', (449, 923, 634, 737)), ('Name3', (1062, 1749, 1216, 1594))]
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23