I'm in the middle of a larger script and need to order a list by the index of the sub lists. My root list contains sub-lists of numbers corresponding to [Latitude, Longitude, Elevation, Distance]. I need to sort the root list by Distance in the sub lists. Any ideas?
Asked
Active
Viewed 806 times
0
-
possible duplicate of [Sorting list based on values from another list?](http://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – YXD Apr 15 '13 at 20:30
-
Can you give some example code or lists? – Elmar Peise Apr 15 '13 at 20:32
2 Answers
3
you can use an operator.itemgetter
to sort the list based on an element of your list:
import operator
lst = [...]
lst.sort(key=operator.itemgetter(3))

mata
- 67,110
- 10
- 163
- 162
1
You need to say explicitly what is the value you want the list to be sorted by; in your case this 4th element of each element of your list. One way you can do it is to use key
keyword parameter of the sort
method and pass to it a function (lambda) which extracts that element:
>>> l = [[1,2,3,3],[1,2,3,2],[1,2,3,1]]
>>> l.sort(key=lambda s: s[3])
>>> l
[[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3]]
>>>

piokuc
- 25,594
- 11
- 72
- 102