In Python you can for example sort tuples sorted([(2,2),(1,2),(2,1),(1,1)])
and get [(1, 1), (1, 2), (2, 1), (2, 2)]
.
You can also use custom k
You could create a mapper function, that takes your key function and returns another function, applying the key function to each element of some iterable.
def mapper(function):
def inner(values):
return tuple([function(x) for x in values])
return inner
Example:
>>>sorted([('Gold', 2), ('Bronze', 1), ('Gold', 1)], key=mapper(custom_key))
[('Gold', 1), ('Gold', 2), ('Bronze', 1)]
Or similar, using functools.partial with map
:
>>> sorted([('Gold', 2), ('Bronze', 1), ('Gold', 1)], key=functools.partial(map, custom_key))
[('Gold', 1), ('Gold', 2), ('Bronze', 1)]