Python sorting key function supporting tuples and lists

后端 未结 4 639
你的背包
你的背包 2021-01-22 08:09

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

4条回答
  •  时光取名叫无心
    2021-01-22 08:35

    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)]
    

提交回复
热议问题