Comparable classes in Python 3

后端 未结 5 1326
北恋
北恋 2020-11-30 07:54

What is the standard way of making a class comparable in Python 3? (For example, by id.)

5条回答
  •  天涯浪人
    2020-11-30 08:30

    You said you are trying to do this:

    max((f(obj), obj) for obj in obj_list)[1]
    

    You should simply do this:

    max(f(obj) for obj in obj_list)
    

    EDIT: Or as gnibbler said: max(obj_list, key=f)

    But you told gnibbler you need an object reference to the max object. I think this is simplest:

    def max_obj(obj_list, max_fn):
        if not obj_list:
            return None
    
        obj_max = obj_list[0]
        f_max = max_fn(obj)
    
        for obj in obj_list[1:]:
            if max_fn(obj) > f_max:
                obj_max = obj
        return obj_max
    
    obj = max_obj(obj_list)
    

    Of course you might want to let it raise an exception rather than return none if you try to find the max_obj() of an empty list.

提交回复
热议问题