Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the characteristics of the Python function sorted ()

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the characteristics of Python function sorted ()". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the characteristics of Python function sorted ()".

1. Compatibility with any iterator

The first reason is that the sorted () function is more flexible because it can be used with any iterable object. By contrast, the sort () function applies only to lists. If you don't know what iterates are, you can refer to my previous article below. In short, iterable objects are Python objects that can be iterated in iterations, such as tuples, lists, collections, and dictionaries.

Let's compare sorted () and sort () based on compatible data types. One thing to note is that there is a slight difference in the way these two functions are used. The sorted () function takes iterable as an argument, while the caller of the sort () function calls the function using dot notation.

> > # sort a tuple > _ = (3,5,4). Sort () Traceback (most recent call last): File ", line 1, in AttributeError: 'tuple' object has no attribute' sort' > _ = sorted ((3,5,4)) > # sort a dictionary > > _ = {2: 'two', 0:' zero', 1: 'one'} .sort (most recent call last): File", line 1 In AttributeError: 'dict' object has no attribute' sort' > _ = sorted ({2: 'two', 0:' zero', 1: 'one'}) > # sort a set > _ = set ([2,3,4]). Sort () Traceback (most recent call last): File ", line 1, in AttributeError:' set' object has no attribute 'sort' > _ = sorted (set ([2,3,4]))

As the above code shows, tuples, dictionaries, and collections cannot call the sort () function. In fact, the sort () function is an instance method of a list object, not an instance method of other collection objects, which means that this function can only be used for list objects. By contrast, tuples, dictionaries, and collections can all be sorted through the sorted () function, because all of these data types are iterable, making them suitable for using the sorted () function.

two。 The convenience of creating lists

The second reason is that the sorted () function will sort the iterable objects in the desired order and return a list object. Therefore, this is a convenient way to build a new list. However, the sort () function changes the order of the list that calls this method, which we call in-place sorting. In addition, this function implicitly returns None (sometimes, we can say that when the implicit return value is None, it returns nothing).

Let's consider the following hypothetical example. Let's start with a dictionary called sales_dict, which keeps sales records for the whole year. We want to create a list of records in descending order based on sales.

> > # records of sales in a dictionary > sales_dict = {'Spring': 1000,' Summer': 1030, 'Fall': 1030,' Winter': 1200} > # create a list object of sales records > sales_list0 = sorted (sales_dict.items (), key=lambda x: X [1], reverse=True) > sales_list0 [('Winter', 1200), (' Fall', 1030), ('Spring', 1000), (' Summer') > sales_list1 = list (sales_dict.items ()) > sales_list1.sort (key=lambda x: X [1], reverse=True) > sales_list1 [('Winter', 1200), (' Fall', 1030), ('Spring', 1000), (' Summer', 1000)]]

In the above code, we only need to write a line of code using the sorted () function to get the desired results. However, with the sort () function, we have to write two lines of code. It is worth noting that because someone may mistakenly think that we cannot use dot symbols to combine these two lines to generate the desired list object.

> # combine the two lines > sales_list2 = list (sales_dict.items ()) .sort (key=lambda x: X [1], reverse=True) > > sales_list2 > type (sales_list2) > print (sales_list2) None

As the code above shows, by combining the two lines, we get the value of none. This is because the return value of the sort () function is None, not the list object that called the function.

3. Integration with iteration

Since the sorted () function returns a list and the sort () function returns None, what does this difference mean? Well, in many cases, we expect an iterable object, but no NoneType object. One such scenario is iteration, which is, after all, a key operation that we often perform with list objects.

Consider the following example. We have two dictionaries that keep the scores of the first semester and the second semester respectively. The goal is to create a report card that summarizes each student's performance and sorts it by name.

> > # test results for the first semester > results1 = {'John': 95,' Danny': 80, 'Zack': 98} > # test results for the second semester > results2 = {' Danny': 84, 'Zack': 95,' John': 88} > # generate the report card > for name, score in sorted (results2.items ()):. Print (f'{name} | Spring: {results1 [name]} | Fall: {score}'). Danny | Spring: 80 | Fall: 84 John | Spring: 95 | Fall: 88 Zack | Spring: 98 | Fall: 95

In the above code, we notice that neither of these dictionaries has the desired output order, so we will use the sorted () function to sort the dictionaries. As you can see, we can integrate the sorted results directly into the for loop, because the sorted () function returns the sorted list.

You may have expected what would happen if we tried to use the sort () function in this case. Please refer to more details below.

> for name, score in list (results2.items ()). Sort ():. Print (f'{name} | Spring: {results1 [name]} | Fall: {score}'). Traceback (most recent call last): File ", line 1, in TypeError: 'NoneType' object is not iterable Thank you for reading, this is the content of" what are the characteristics of Python function sorted () ". After the study of this article, I believe you have a more profound understanding of the characteristics of Python function sorted (). The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report