0

Given: lst = [['John',3],['Blake',4],['Ted',3]]

Result: lst = [['John',3],['Ted',3],['Blake',4]]

I'm looking for a way to sort lists in lists first numerically then alphabetically without the use of the "itemgetter" syntax.

5 Answers 5

5

Since you insist:

lst.sort(key=lambda x: x[::-1])
Sign up to request clarification or add additional context in comments.

Comments

2

You could use the argument key from the built-in sorted function.

In this key argument, you pass a function with one parameter, that returns something that will be sorted instead of sorting the list by its elements.

def my_func(elem):
    # return a tuple (second element, first element)
    return (elem[1], elem[0])

>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> sorted(lst, key=my_func)
[['John', 3], ['Ted', 3], ['Blake', 4]]

Or even shorter:

>>> sorted(lst, key=lambda x: (x[1],x[0]))
[['John', 3], ['Ted', 3], ['Blake', 4]]

In both ways, you sort first numerically, then alphabetically.

1 Comment

I think Python suggest using sorted() before .sort() docs.python.org/howto/sorting.html#sorting-basics
2

I think this may have been asked before in the following question:

Sorting a list of lists in Python

Here is the explanation given by Dave Webb:

The key argument to sort specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambda that returns the last element from each row to be used in the sort:

c2.sort(key = lambda row: row[2])

A lambda is a simple anonymous function. It's handy when you want to create a simple single use function like this. The equivalent code not using a lambda would be:

def sort_key(row):
    return row[2]

c2.sort(key = sort_key)

If you want to sort on more entries, just make the key function return a tuple containing the values you wish to sort on in order of importance. For example:

c2.sort(key = lambda row: (row[2],row[1]))

or:

c2.sort(key = lambda row: (row[2],row[1],row[0]))

Comments

1

What's wrong with itemgetter?

lst.sort(key=lambda l: list(reversed(l)) should do the trick

Comments

0

In Python2, you can use this

>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> lst.sort(key=sorted)
>>> lst
[['John', 3], ['Ted', 3], ['Blake', 4]]

This works because ints are always "less than" strings in Python2

You can no longer sort str and int objects in Python3 though

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.