Home  >  Article  >  Backend Development  >  Sorted(): My favorite function in Python

Sorted(): My favorite function in Python

WBOY
WBOYforward
2023-09-05 20:21:031246browse

Sorted(): My favorite function in Python

Introduction

In Python, the sorted() function is one of the most basic yet useful methods you need to know to start sorting. This function can be used to sort the elements of iterable objects, such as lists, strings, etc. This function sorts strings and numbers. By default, it sorts in ascending order, but it can also be sorted in descending order.

How to use the Sorted() function

  • Use the Sorted() function to sort numbers

  • Sort lists, tuples, sets and dictionaries

  • Sort strings

  • Sort inside lambda function

Method 1: Use the Sorted() function to sort numbers

The most basic implementation of the sorted() function is to sort a collection of integers (signed or unsigned). This can be done in ascending or descending order.

grammar

print(sorted([n1, n2, n3, n4]))

The syntax is very simple. We just pass the numbers we want to sort as an argument to the sort function and it will return the numbers in sorted order. To sort in descending order, we need to add the word "reverse" after the list of numbers. One thing to note here is that the numbers must be placed in an iterable container for this method to work.

algorithm

Step 1 - Call the sorted() function

Step 2 - Pass the list of numbers as a parameter and use the "reverse" keyword if needed

Step 3 - Return or print output

The Chinese translation of

Example

is:

Example

print(sorted([4, 1, 3, 2]))

Output

[1, 2, 3, 4] 

Method 2: Sort lists, tuples, sets and dictionaries

The contents of sequences (such as lists, tuples, strings) and sets (such as sets, frozen sets, and data sets) can be sorted using the sorted() method. This function is part of Python's built-in library, so you can easily sort things without writing a lot of code.

grammar

define x=container/set
return(sorted(x))

This simple syntax is one of my favorite reasons for the sorted() function, and it is very easy to apply. In order to sort the contents of any type of iterator, we first declare the iterator, like list, set, etc. This iterator is then passed to the function, which then returns the sorted contents.

algorithm

Step 1 - Initialize the iterator with the elements to be sorted

Step 2 - Pass the iterator as argument to the sorted() method, along with the key and ascending or descending order confirmation

Step 3 - Print or return value

The Chinese translation of

Example

is:

Example

# List
x = ['z', 'g', 'e', 'o', 't', 'y']
print(sorted(x))

# Tuple
x = ('z', 'g', 'e', 'o', 'd', 'k')
print(sorted(x))

# Dictionary
x = {'z': 1, 'p': 2, 'e': 12, 'h': 8, 'k': 7, 'y': 3}
print(sorted(x))

# Set
x = {'x', 'w', 'h', 'd', 'k', 'b'}
print(sorted(x))

# Frozen Set
x = frozenset(("v", "m", "d", "u", "s", "c"))
print(sorted(x))

Output

['e', 'g', 'o', 't', 'y', 'z']
['d', 'e', 'g', 'k', 'o', 'z']
['e', 'h', 'k', 'p', 'y', 'z']
['b', 'd', 'h', 'k', 'w', 'x']
['c', 'd', 'm', 's', 'u', 'v'] 

Method 3: String sorting

The availability of the sorted() function is not limited to numbers, but can also be used for strings. Strings can be sorted lexicographically using ASCII values, and can be sorted in ascending and descending order. This way, we can also reverse the string after sorting or perform other applications.

grammar

res = ''.join(sorted(test_string, reverse = True))

This is the syntax for reversing a string. We use the join function and the sorted() method, and set the reverse flag to True. This ensures that the string is reversed and sorted in descending order.

algorithm

Step 1− Initialize string for reversal

Step 2 - Call the join() and sorted() methods

Step 3 - Pass the string and reverse flag to the sorted() function

The Chinese translation of

Example

is:

Example

test_string = "tutorialspoint"
print("The original string : " + str(test_string))
res = ''.join(sorted(test_string, reverse = True))
print("String after reverse sorting : " + str(res))

Output

The original string : tutorialspoint
String after reverse sorting : utttsrpoonliia 

Method 4: Sorting inside lambda function

Lambda function is a type of anonymous function in Python. They are declared using the lambda keyword and can contain only one expression, but can contain an unlimited number of parameters.

grammar

res = functools.reduce(lambda x, y: x + y,
 sorted(test_string, reverse=True))

Through the above syntax, you can observe the result of sorting and reversing the test string, in which we use the reduce() function. The sort function is used to perform the actual sorting, while the lambda function takes two inputs and returns their sum as function output.

algorithm

Step 1 - Import functools module

Step 2 - Define the test string

Step 3 - Pass the test string to the reduce() function according to the grammar

Step 4 - Print the reversed string

The Chinese translation of

Example

is:

Example

# import the module
import functools
test_string = "tutorialspoint"
print("The original string : " + str(test_string))
res = functools.reduce(lambda x, y: x + y,  sorted(test_string,  reverse=True))
print("String after reverse sorting : " + str(res))

Output

The original string : tutorialspoint
String after reverse sorting : utttsrpoonliia 

in conclusion

In this article, we learned about the various uses of the sorted() function. The versatility and simple application of this feature make it ideal for initial use in many processes. There may be several other use cases for this function, although all of them cannot be discussed here. I hope this article was helpful in learning a very useful function in Python!

The above is the detailed content of Sorted(): My favorite function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete