Sorting list by an attribute that can be None

前端 未结 4 705
栀梦
栀梦 2020-11-30 09:53

I\'m trying to sort a list of objects using

my_list.sort(key=operator.attrgetter(attr_name))

but if any of the list items has attr = None

4条回答
  •  时光说笑
    2020-11-30 10:24

    For a general solution, you can define an object that compares less than any other object:

    from functools import total_ordering
    
    @total_ordering
    class MinType(object):
        def __le__(self, other):
            return True
    
        def __eq__(self, other):
            return (self is other)
    
    Min = MinType()
    

    Then use a sort key that substitutes Min for any None values in the list

    mylist.sort(key=lambda x: Min if x is None else x)
    

提交回复
热议问题