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.

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
HighAllegiant
  • 61
  • 3
  • 9

5 Answers5

5

Since you insist:

lst.sort(key=lambda x: x[::-1])
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
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]))
Community
  • 1
  • 1
ozdrgnaDiies
  • 1,909
  • 1
  • 19
  • 34
1

What's wrong with itemgetter?

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

Miki Tebeka
  • 13,428
  • 4
  • 37
  • 49
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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502