James Pritchard
James Pritchard

Reputation: 79

Python Sorting a list of lists

I am currently trying to sort a list such as the following. I need to sort the lists in order of the second element in each sub-list.

chars = [['Andrew', '1'], ['James', '12'], ['Sam', '123'], ['Zane', '2']]

I am currently using this command:

chars = sorted(chars, key=itemgetter(1))

My Ideal output would be:

chars = [['Andrew', '1'], ['Zane', '2'], ['James', '12'], ['Sam', '123']]

Upvotes: 1

Views: 172

Answers (2)

huang
huang

Reputation: 519

def myCmp(x, y):
    if int(x[1])>int(y[1]):
        return 1
    else:
        return -1

chars.sort(cmp=myCmp)#chars.sort(key=lambda x:int(x[1]))

print chars

output:

[['Andrew', '1'], ['Zane', '2'], ['James', '12'], ['Sam', '123']]

Maybe can help you.

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

You need to convert second element into integer first for sorting:

>>> sorted(chars, key=lambda x: int(x[1]))
[['Andrew', '1'], ['Zane', '2'], ['James', '12'], ['Sam', '123']]

If you want to do it using operator.itemgetter:

>>> sorted(chars, key=lambda x: int(itemgetter(1)(x)))
[['Andrew', '1'], ['Zane', '2'], ['James', '12'], ['Sam', '123']]

Upvotes: 10

Related Questions