Sorting list by an attribute that can be None

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

    Since there are other things besides None that are not comparable to a string (ints and lists, for starters), here is a more robust solution to the general problem:

    my_list.sort(key=lambda x: x if isinstance(x, str) else "")
    

    This will let strings and any type derived from str to compare as themselves, and bin everything else with the empty string. Or substitute a different default default key if you prefer, e.g. "ZZZZ" or chr(sys.maxunicode) to make such elements sort at the end.

提交回复
热议问题