Custom Sorting Functions in Python

Custom Sorting Functions in Python

Custom sorting functions allow you to precisely control how elements in a list are sorted by defining specific criteria. The key parameter in the sort() and sorted() methods is used to specify these custom sorting criteria.

Using key for Custom Sorting

The key parameter accepts a function that takes an element from the list and returns a value to be used for sorting. Python then sorts the elements based on these key values.

Basic Example

Suppose you have a list of strings and you want to sort them by their length: 

# List of strings
words = ["apple", "banana", "cherry", "kiwi"]
# Sort by length of strings
words.sort(key=len)
print("Sorted by length:", words)
"""
Output:
Sorted by length: ['kiwi', 'apple', 'cherry', 'banana']
"""

Sorting by Object Attributes

For more complex objects, such as instances of classes, you can use a key function to access object attributes.

Example with a Class

Assume you have a Person class with name and age attributes: 

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self):
        return f"{self.name} ({self.age} years old)"
# List of people
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
# Sort by age
people.sort(key=lambda p: p.age)
print("Sorted by age:", people)
"""
Output:
Sorted by age: [Bob (25 years old), Alice (30 years old), Charlie (35 years old)]
"""

Sorting with Multiple Criteria

You can also sort based on multiple criteria by using tuples as the key.

Example with Multiple Criteria

Suppose you want to sort a list of tuples first by the second element and then by the first element in case of ties: 

# List of tuples
data = [("apple", 3), ("banana", 2), ("cherry", 3), ("kiwi", 1)]
# Sort by the second element, then by the first element
data.sort(key=lambda x: (x[1], x[0]))
print("Sorted by multiple criteria:", data)
"""
Output:
Sorted by multiple criteria: [('kiwi', 1), ('banana', 2), ('apple', 3), ('cherry', 3)]
"""

Custom Key Functions

You can define more complex key functions for specialized sorting needs.

Example with a Custom Key Function

Suppose you want to sort strings by the sum of the ASCII values of their characters: 

def ascii_sum(s):
    return sum(ord(c) for c in s)
# List of strings
strings = ["abc", "def", "ghi", "xyz"]
# Sort by the sum of ASCII values
strings.sort(key=ascii_sum)
print("Sorted by ASCII sum:", strings)
"""
Output:
orted by ASCII sum: ['abc', 'def', 'ghi', 'xyz']
"""

Descending Order with Custom Key Function

You can combine descending order sorting with a custom key function by using reverse=True.

Example with Descending Order and Custom Key 

# List of strings
strings = ["apple", "banana", "cherry", "kiwi"]
# Sort in descending order by length of strings
strings.sort(key=len, reverse=True)
print("Descending order by length:", strings)
"""
Output:
Descending order by length: ['banana', 'cherry', 'apple', 'kiwi']
"""

Using sorted() with Custom Key Functions

If you want to keep the original list unchanged, use sorted() with a custom key function.

Example with sorted() and Custom Key 

# List of strings
strings = ["apple", "banana", "cherry", "kiwi"]
# Sort by length of strings with sorted()
sorted_strings = sorted(strings, key=len)
print("Sorted by length with sorted():", sorted_strings)
print("Original list:", strings)
"""
Output:
Sorted by length with sorted(): ['kiwi', 'apple', 'cherry', 'banana']
Original list: ['apple', 'banana', 'cherry', 'kiwi']
"""

Summary

  • Using key: Allows sorting elements based on a key extracted by a key function.
  • Object Attributes: Sort objects by their attributes using a key function.
  • Multiple Criteria: Sort by multiple criteria using tuples as keys.
  • Custom Key Functions: Define complex key functions for specialized sorting needs.
  • Descending Order with Key: Combine descending order with a custom key function using reverse=True.
  • Using sorted(): Keeps the original list unchanged while sorting with a custom key function.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *