method ‘sort’ of ‘list’ objects
时间: 2024-06-04 07:13:57 浏览: 77
The ‘sort’ method of ‘list’ objects is used to sort the elements of a list in ascending or descending order. It modifies the original list and does not return anything.
The syntax of the ‘sort’ method is:
list.sort(key=None, reverse=False)
Here, ‘key’ is an optional parameter that specifies a function to be applied to each element before sorting. ‘reverse’ is also an optional parameter that specifies whether to sort the list in descending order or not.
Examples:
# Sorting a list of numbers in ascending order
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# Sorting a list of strings in descending order
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
fruits.sort(reverse=True)
print(fruits) # Output: ['elderberry', 'date', 'cherry', 'banana', 'apple']
# Sorting a list of tuples based on the second element in ascending order
students = [('Alice', 20), ('Bob', 18), ('Charlie', 22), ('Dave', 19)]
students.sort(key=lambda x: x[1])
print(students) # Output: [('Bob', 18), ('Dave', 19), ('Alice', 20), ('Charlie', 22)]
阅读全文