How can I sort the following based on the 1st element?
list1 = [["Value313",1],["Value421",3],["Value234",2]]
Ultimately, I should get the following:
list1 = [["Value234",2],["Value313",1],["Value421",3]]
How can I sort the following based on the 1st element?
list1 = [["Value313",1],["Value421",3],["Value234",2]]
Ultimately, I should get the following:
list1 = [["Value234",2],["Value313",1],["Value421",3]]
The default sort order of lists (lexicographically) is already how you want it.
>>> list1 = [["Value313",1],["Value421",3],["Value234",2]]
>>> list1.sort()
>>> print list1
[['Value234', 2], ['Value313', 1], ['Value421', 3]]
sorted(list1,key=lambda x : x[0])
[['Value234', 2], ['Value313', 1], ['Value421', 3]]
Use sorted and use a key lambda x[0]
where x[0]
is the first element in each sublist
Or sort in place to avoid creating a new list:
list1 = [["Value313",1],["Value421",3],["Value234",2]]
list.sort(list1,key=lambda x : x[0])
print list1
[['Value234', 2], ['Value313', 1], ['Value421', 3]]
To sort list1
in place (without creating another list) use:
from operator import itemgetter
list1.sort(key=itemgetter(0))
If you want to create another list and leave list1
unsorted use:
from operator import itemgetter
list2 = sorted(list1, key=itemgetter(0))
You could use a lambda, but operator.itemgetter normally has better performance since it's at C level.