Reputation: 71
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.
Upvotes: 0
Views: 1342
Reputation: 304175
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
Upvotes: 0
Reputation: 1929
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]))
Upvotes: 2
Reputation: 24921
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.
Upvotes: 2
Reputation: 13850
What's wrong with itemgetter?
lst.sort(key=lambda l: list(reversed(l))
should do the trick
Upvotes: 1
Reputation: 798676
Since you insist:
lst.sort(key=lambda x: x[::-1])
Upvotes: 5