0

I'm looking to take a list of lists and sort them by an element contained in the contained lists. For clarification, I want to have a list like this code

myList = []
myList.append([1, 2, 3])
myList.append([1, 1, 1])
myList.append([1, 3, 2])

and then sort the elements of list by the last element of each contained list and it would end up looking like this

           |
myList = ( v
    [1, 2, 3],
    [1, 3, 2],
    [1, 1, 1])

I also have the numpy library imported in this project. I was looking at argsort for numpy but I don't think you can sort it along an axis of an element

4
  • 2
    Don't use list as a variable name because it's built into python. Commented Nov 15, 2019 at 4:09
  • Does this need to be time and space efficient or are there not many items in this list? Commented Nov 15, 2019 at 4:10
  • I will be having a few hundred thousand items in the lists. Commented Nov 15, 2019 at 4:13
  • Possible duplicate of Sorting list of lists by the first element of each sub-list Commented Nov 15, 2019 at 4:18

1 Answer 1

2

First of all don't use list as variable name as it is one of python built-in function, and second you can use sorted function to sort by position

l = []
l.append([1, 2, 3])
l.append([1, 1, 1])
l.append([1, 3, 2])
sorted(l,key = lambda x : x[2])
#[[1, 1, 1], [1, 3, 2], [1, 2, 3]]
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know about this. Thanks, exactly what I was looking for.
lambda x : x[-1] will be more general to pick last element
l (el) isn't a good variable name. It looks like a '1' (one) in many fonts. Can use the operator library: my_list.sort(key=operator.itemgetter(-1))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.