Python sorting key function supporting tuples and lists

后端 未结 4 638
你的背包
你的背包 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:29

    from collections import Iterable
    def custom_key(item):
        if isinstance(item, Iterable) and not isinstance(item, basestring):
            return [medals_map.get(ele, ele) for ele in item]
        return medals_map.get(item, item)
    

    Output:

    In [2]: assert sorted(['Silver', 'Bronze', 'Gold'], key=custom_key) == ['Gold', 'Silver', 'Bronze']
    
    In [3]: assert sorted([['Silver', 2], ['Silver', 1], ['Gold', 1]], key=custom_key) == [['Gold', 1], ['Silver', 1], ['Silver', 2]]
    
    In [4]: assert sorted([(2, 'Gold'), (2, 'Bronze'), (1, 'Gold')], key=custom_key) == [(1, 'Gold'), (2, 'Gold'), (2, 'Bronze')]
    
    In [5]: assert sorted([('Silver', 'Bronze'), ('Gold', 'Bronze'), ('Silver', 'Gold')], key=custom_key) == [('Gold', 'Bronze'), ('Silver', 'Gold'), ('Silver', 'Bronze')]
    

提交回复
热议问题