0

In Python I have a list of objects, and I can sort them by attributes a or b using

obj_list = sorted(obj_list, key=lambda x:x.a)

or

obj_list = sorted(obj_list, key=lambda x:x.b)

The sort selected (a or b or many other options) depends on user input, so I'd like to be able to have a single sorting statement and pass it the sort key – something like this:

def sortfunc(attribute):
    return lambda x:attribute

I know that won't work, but is there a way to do this?

2
  • You can just not use lambda and go for a normal function that does the check. Commented Oct 19, 2022 at 11:34
  • lambda x: getattr(x, attribute) Commented Oct 19, 2022 at 11:36

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.