-1

Suppose, we have sequence of instances of one class. Let's describe class

class Person:
    def __init__(self, name, lastname):
        self.name = name
        self.lastname = lastname

Creating instances:

obj1 = Person('Andrew', 'Martin')
obj2 = Person('Mark', 'Levy')
obj3 = Person('Harry', 'Anderson')
objs = (obj1, obj2, obj3)

I want to return the maximum from the tuple in two fields. Something like the following:

from operator import attrgetter
max_obj = max(objs, key=(attrgetter('lastname'), attrgetter('name')))

Such code raise an error

(TypeError: 'tuple' object is not callable).

How, then, can one get the maximum?

Itay
  • 16,601
  • 2
  • 51
  • 72

1 Answers1

1

You can concatenate these properties in the key using a lambda function:

max_obj = max(objs, key=lambda x: x.lastname.lower() + x.name.lower())

For instance:

obj1 = Person('George', 'Martin')
obj2 = Person('Beth', 'Martin')
obj3 = Person('Mark', 'Levy')
obj4 = Person('Harry', 'Anderson')
objs = (obj1, obj2, obj3, obj4)

from operator import attrgetter
max_obj = max(objs, key=lambda x: x.lastname.lower() + x.name.lower())
print(max_obj.name)

Out: George

More on using functions as keys for the max function can be found here.

Itay
  • 16,601
  • 2
  • 51
  • 72