Sorting list by an attribute that can be None

前端 未结 4 704
栀梦
栀梦 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:10

    The solutions proposed here work, but this could be shortened further:

    mylist.sort(key=lambda x: x or 0)
    

    In essence, we can treat None as if it had value 0.

    E.g.:

    >>> mylist = [3, 1, None, None, 2, 0]
    >>> mylist.sort(key=lambda x: x or 0)
    >>> mylist
    [None, None, 0, 1, 2, 3]
    

提交回复
热议问题