How to use the sorted function in Python?

In Python, the sorted() function can be used to sort iterable objects such as lists, tuples, dictionaries, and more.

Syntax:
sorted(iterable, key=None, reverse=False)

Explanation of parameters:

  1. Iterable: a mandatory parameter that represents the iterable object to be sorted, such as a list, tuple, dictionary, etc.
  2. The key parameter is optional and can be used to specify a function that determines how to sort the iterable object based on its return value. If not specified, the elements will be sorted in their natural order.
  3. reverse: Optional, indicating whether to reverse the sorting order. By default, it is set to False, indicating sorting in ascending order.

原文:我在做市场研究方面有着丰富的经验。
Paraphrase: I have extensive experience in market research.

  1. Sort the list.
numbers = [5, 2, 8, 3, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 2, 3, 5, 8]
  1. Sort the tuple.
fruits = ("apple", "banana", "cherry")
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # 输出:['apple', 'banana', 'cherry']
  1. Sort the dictionary.
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)  # 输出:[('Bob', 92), ('Alice', 85), ('Charlie', 78)]

In the example above, a lambda expression is used as the key parameter to sort the dictionary based on its values. The reverse parameter is set to True, indicating a descending order of sorting.

bannerAds