To sort a list of objects (List<T>
) by a specific property in the objects, you can use the sort()
or sorted()
function in Python. Here's an example demonstrating how to do this:
Suppose you have a list of objects of a class called Person
, and you want to sort the list based on the age
property of each person.
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create a list of Person objects
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 22),
Person("David", 28)
]
# Sort the list of people based on the 'age' property
sorted_people = sorted(people, key=lambda person: person.age)
# Print the sorted list
for person in sorted_people:
print(person.name, person.age)
In this example:
- We define a
Person
class with a constructor that initializes thename
andage
properties. - We create a list named
people
containing instances of thePerson
class. - We use the
sorted()
function to sort the list based on theage
property. Thekey
parameter specifies the function that returns the value to be used for sorting (in this case,person.age
). - We use a lambda function as the
key
to extract theage
property for each person. - The sorted list is stored in the
sorted_people
variable. - We loop through the sorted list and print the names and ages of the people.
The output of the example will be:
Charlie 22 Alice 25 David 28 Bob 30
The sorted()
function returns a new sorted list without modifying the original list. If you want to sort the list in-place, you can use the sort()
method of the list:
python
people.sort(key=lambda person: person.age)
Both the sorted()
function and the sort()
method allow you to sort a list of objects by a specific property in the objects.
Comments
Post a Comment