SSBlur
SSBlur

Reputation: 53

Sorting List of Lists of Strings and Integers

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

Answers (2)

alecxe
alecxe

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

Harpal
Harpal

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

Related Questions