3

Say I have a nested list of objects that have a method called get_name(), which gives you a name for the object, and you have to sort the lists by alphabetical order.

my_list = [[obj1, obj2, obj3], [obj4, obj5, obj6], [obj7, obj8]]

But I don't know how to make it work with a list of objects, specifically with get_name() as the main method to use, it also has to be assumed that only the list within the list has to be sorted.

Any help is appreciated!

2 Answers 2

3

How about simple for loop?

comparator = lambda obj: obj.get_name()
for sub_list in my_list:
    sub_list.sort(key=comparator)
Sign up to request clarification or add additional context in comments.

Comments

1

It could be as simple as:

for sub in my_list:
    sub.sort(key=MyClass.get_name)

This will sort each sublist in-place, using the result of get_name() to determine the order.

2 Comments

That will only work if all the objects are instances of MyClass which is not necessarily true.
@stasdeep: Rather than obliquely complain about my answer, why not call attention to the merits of your own by explaining in an edit why one might choose to use a lambda rather than a direct function call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.