python list sort
时间: 2023-11-13 12:04:01 浏览: 90
The sort() method in Python is used to sort the elements of a list in ascending or descending order.
Syntax: list.sort(reverse=True|False, key=myFunc)
Here,
- reverse: Optional. Specifies whether the list should be sorted in ascending or descending order. Default is False (ascending order).
- key: Optional. A function to specify the sorting criteria(s).
Example:
# sorting a list in ascending order
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
fruits.sort()
print(fruits) # Output: ['apple', 'banana', 'cherry', 'kiwi', 'mango']
# sorting a list in descending order
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
fruits.sort(reverse=True)
print(fruits) # Output: ['mango', 'kiwi', 'cherry', 'banana', 'apple']
# sorting a list based on the length of each element
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
fruits.sort(key=len)
print(fruits) # Output: ['kiwi', 'apple', 'mango', 'banana', 'cherry']
阅读全文