1

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']]
1
  • 2
    For completeness, you should post the output you're getting. Commented Sep 18, 2015 at 7:56

2 Answers 2

10

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']]
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.