Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a nested list of Objects with specific method

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!

like image 541
Lebcode Avatar asked May 20 '26 01:05

Lebcode


2 Answers

How about simple for loop?

comparator = lambda obj: obj.get_name()
for sub_list in my_list:
    sub_list.sort(key=comparator)
like image 178
stasdeep Avatar answered May 22 '26 15:05

stasdeep


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.

like image 31
John Zwinck Avatar answered May 22 '26 14:05

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!