One article to understand the sort and sorted functions in Python

1 Introduction

sort()The sum function in Python sorted()is mainly used to sort data in ascending or descending order. This article compares the programming and syntax differences between the two functions when used with lists.

Without further ado, let's get started!

2. Basic usage of Sort() function

The syntax of the sort function for sorting a list is as follows:

list.sort(reverse=False, key=None)

The usage is as follows:

  • Parameter reverse: The default is False. If reverse=True, the data will be sorted in descending order.
  • Parameter key: The default is None. We can specify a user-defined function to customize the sorting.

2.1 Basic sorting of example 1

Let's first try to use the above default parameters to see an example. The sample code is as follows:

# Original List
typ_data = ['$', '45', '3j+5', 'Hello']
print(f'Original Data: {typ_data}')

# Sorting the list
typ_data.sort()
# Printing sorted list
print(f'Sorted Data: {typ_data}')

----------
Original Data: ['$', '45', '3j+5', 'Hello']
Sorted Data: ['$', '3j+5', '45', 'Hello']

It can be known that the above results are sorted in ascending order according to the ASCII code of the first character of the string.

2.2 Example 2 User-defined sorting function

Sometimes we need to sort the list according to the user-defined function, the corresponding code example is as follows:

# List containing dictionary data
data = [
    {
    
    'fruit': 'strawberry', 'price': 100},
    {
    
    'fruit': 'banana', 'price': 91},
    {
    
    'fruit': 'mango', 'price': 132},
    {
    
    'fruit': 'cherry', 'price': 82},
]

print(f'Original Data: {data}')

# Function for sorting by key 'price'
def sort_dict_by_price(item):
    return item['price']

# Sorting data using the user-defined sorting function
data.sort(key=sort_dict_by_price)
print('-'*20)
# Printing the data
print(f'Sorted Data: {data}')

The result of the operation is as follows:

Original Data: [{
    
    'fruit': 'strawberry', 'price': 100}, {
    
    'fruit': 'banana', 'price': 91}, {
    
    'fruit': 'mango', 'price': 132}, {
    
    'fruit': 'cherry', 'price': 82}]
--------------------
Sorted Data: [{
    
    'fruit': 'cherry', 'price': 82}, {
    
    'fruit': 'banana', 'price': 91}, {
    
    'fruit': 'strawberry', 'price': 100}, {
    
    'fruit': 'mango', 'price': 132}]

In the above code, we did this by writing a sort_dict_by_pricefunction called , which takes our dictionary itself as input, and returns the value for the key "price". Pass this function sortthe parameter of the function keythat will sort the data in ascending order according to the price.

3. Basic usage of Sorted() function

The syntax of the sorted function for sorting lists is as follows:

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

The usage is as follows:

  • Parameters iterable: Required. input any iterable data
  • Parameter key: The default is "None". Specify sorting criteria.
  • Parameter reverse: The default is False. When set to True, the data will be sorted in descending order.

3.1 Basic sorting of example 1

Functions in Python sorted()are used to sort iterable data. By default, this function sorts the data in ascending order.

Of course, we can also use sortedfunctions to sort various types of data. The sample code is as follows:

list_data = [43, 21, 2, 34]
print(f'Sorted List: {sorted(list_data)}')

# Seperator
print('-'*20)

tuple_data = (('x', 3), ('w', 1), ('1', 4))
print(f'Sorted Tuple: {
    
    sorted(tuple_data)}')

# Seperator
print('-'*20)

dict_data = {
    
    9: 'G', 1: 'V', 4: 'E'}
print(f'Sorted Dictionary Keys: {
    
    sorted(dict_data)}')
print(f'Sorted Dictionary Values: {
    
    sorted(dict_data.values())}')
print(f'Sorted Dictionary Items: {
    
    sorted(dict_data.items())}')

The result is as follows:

Sorted List: [2, 21, 34, 43]
--------------------
Sorted Tuple: [('1', 4), ('w', 1), ('x', 3)]
--------------------
Sorted Dictionary Keys: [1, 4, 9]
Sorted Dictionary Values: ['E', 'G', 'V']
Sorted Dictionary Items: [(1, 'V'), (4, 'E'), (9, 'G')]

3.2 Example 2 User-defined sorting function

We can also sorted()implement the corresponding sorting function by passing a custom sorting function to the function, for example as follows:

# Tuple data
tuple_data = (
    ('Mango', 25),
    ('Walnut', 65),
    ('Cherry', 10),
    ('Apple', 68),
)

print(f'Original: {tuple_data}')
# Separator
print('-'*20)

# Function for grabbing 2nd item from the data
def sorting_tup_data(item):
    return item[1]

# Sorting based on sorting criteria in descending order
sorting = sorted(tuple_data, key=sorting_tup_data, reverse=True)
print(f'Sorted: {sorting}')

The result is as follows:

Original: (('Mango', 25), ('Walnut', 65), ('Cherry', 10), ('Apple', 68))
--------------------
Sorted: [('Apple', 68), ('Walnut', 65), ('Mango', 25), ('Cherry', 10)]

In the above code, because the parameters are used when passing the custom function key, the tuples are sorted according to the second item; also because we set the parameter reverseto True, the output data is sorted and output in descending order.

4. Summary

We've seen a comparison of sort()and sorted()functions for lists, and we've given corresponding code examples to see how these functions work. In short, both functions are used to sort data, but functions sort()only sort Python lists, while sorted()functions are used to sort iterable data.

The above is summarized as follows:

insert image description here

Guess you like

Origin blog.csdn.net/sgzqc/article/details/130041076