0

I need to sort a list of vectors, based on the last element of the vector. I thought it should be possible with the list.sort(key=something) method, but all I find are examples using the sorted() function, and I'm not clear how that key=something could point to the last element of the vector.

Here is my list of 3 vectors:

[ [1,2], [2,3], [3,1] ]

I need to reorder the 3 vectors by using the second element of each vector, and the result should produce the following

[ [3,1], [1,2], [2,3] ]
karthikr
  • 97,368
  • 26
  • 197
  • 188
gciriani
  • 611
  • 2
  • 7
  • 19

1 Answers1

1

Sure you can do that.

lst = [ [1,2], [2,3], [3,1] ]
def last_val_key(vec):
    return vec[-1]
lst.sort(key=last_val_key)
print lst

Note that the main difference between list.sort and sorted is that list.sort takes the list and sorts it in place whereas sorted creates a new (sorted) list from an arbitrary iterable that you pass in. Both accept a key argument and it does the same thing in both cases.

mgilson
  • 300,191
  • 65
  • 633
  • 696