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!
How about simple for loop?
comparator = lambda obj: obj.get_name()
for sub_list in my_list:
sub_list.sort(key=comparator)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With