Reputation: 53
Okay, so I have a list that contains multiple lists.
The list is formatted like this:
list1 = [["Value1",1],["Value2",3],["Value3",2]]
I would like to sort the inner lists by the second value so that I can, for example, print them in order, like Value1, Value3, Value2.
Any help on how to do this would be appreciated. Thanks in advance!
Upvotes: 0
Views: 1433
Reputation: 473833
You can use sorted()
with an itemgetter()
:
>>> from operator import itemgetter
>>> list1 = [["Value1",1],["Value2",3],["Value3",2]]
>>> sorted(list1, key=itemgetter(1))
[['Value1', 1], ['Value3', 2], ['Value2', 3]]
Upvotes: 3
Reputation: 12577
How about using lambda:
>>> list1 = [["Value1",1],["Value2",3],["Value3",2]]
>>>
>>> list1.sort(key=lambda x: x[1])
>>> list1
[['Value1', 1], ['Value3', 2], ['Value2', 3]]
>>>
Upvotes: 3