Python Number Sorting Guide: Methods & Examples

In Python, you can use the built-in sorted() function or the sort() method of list objects to sort numbers. Here are some examples:

  1. Sort the list of numbers using the sorted() function.
numbers = [5, 2, 8, 1, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
  1. Sort the list of numbers using the sort() method of the list object.
numbers = [5, 2, 8, 1, 6]
numbers.sort()
print(numbers)
  1. Sort the list of numbers in descending order.
numbers = [5, 2, 8, 1, 6]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)
  1. Customize sorting using lambda functions.
numbers = [5, 2, 8, 1, 6]
sorted_numbers = sorted(numbers, key=lambda x: x % 2)  # 按数字奇偶性排序
print(sorted_numbers)

The above are some basic methods for sorting numbers, choose the appropriate method based on specific needs and situations.

bannerAds