Sorted sorting in python

Source: Internet
Author: User

Sorting algorithms that are frequently encountered in programming. I have also introduced some sorting algorithms in several articles. Some advanced languages have built-in sorting functions. This article describes how Python works in this aspect. For the reference of programmers who use python, and for those who do not use python to understand python. Let's take a look at the meaning of "limited life, please use Python.


Use of the built-in function sorted ()/list. sort ()


Simple Application


Python has a built-in function: sorted () for sorting. Example:

>>> A = [5, 3, 6, 1, 9, 2] >>> sorted (a) # After a is sorted, a sorting result [1, 2, 3, 5, 6, 9] # However, the original a is not affected >>> a [5, 3, 6, 1, 9, 2]

You can also use list. sort () to perform the preceding operations.

>>>. Sort () >>> a # note that here, after listing. after sort (), the sequence of the original [1, 2, 3, 5, 6, 9] # a has changed, which is different from the above.

Differences between sorted and list. sort:List. sort () can only sort the list type. As follows:

>>> b_dict={1:'e',3:'m',9:'a',5:'e'}>>> b_dict.sort()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  AttributeError: 'dict' object has no attribute 'sort'

Sorted is not. Let's look at the example:

>>> b_dict{1: 'e', 3: 'm', 5: 'e', 9: 'a'}>>> sorted(b_dict)[1, 3, 5, 9]

After sorted, in dictinoary, the key values are extracted and sorted, and the sorting results of the list type are returned.


Sort by specified keywords


In list. sort () and sorted, you can sort by specified key values. For example:

Sorted example:

>>> Qw = "I am Qiwsir you can read my articles im my blog ". split () >>> qw ['I', 'am ', 'qiwsir', 'you', 'can ', 'read', 'my', 'articles ', 'im ', 'My', 'blog '] >>> sorted (qw, key = str. lower) # Sort ['am', 'articles ', 'blog', 'can ',' I ', 'im', 'My 'in ascending order of letters ', 'My, 'qiwsir ', 'read', 'you']

Example of list. sort:

>>> qw  ['I', 'am', 'Qiwsir', 'you', 'can', 'read', 'my', 'articles', 'im', 'my', 'blog']>>> qw.sort(key=str.lower)>>> qw['am', 'articles', 'blog', 'can', 'I', 'im', 'my', 'my', 'Qiwsir', 'read', 'you']

In addition, the key can receive a single return value of the function, sorted by this value. For example:

>>> Name_mark_age = [('hangsan', 'A', 15), ('lisi', 'B', 14), ('hangzhou', 'A ', 16)] >>> sorted (name_mark_age, key = lambda x: x [2]) # sort by age [('lisi', 'B', 14 ), ('hangsan', 'A', 15), ('hangzhou', 'A', 16)]> sorted (name_mark_age, key = lambda x: x [1]) # sort by level [('hangsan', 'A', 15), ('hangww', 'A', 16), ('lisi ', 'B', 14)] >>> sorted (name_mark_age, key = lambda x: x [0]) # sort by name [('lisi', 'B ', 14), ('hangzhou', 'A', 16), ('hangsan', 'A', 15)]

In addition to the preceding method, python also provides a module for selecting the specified values cyclically. Official documents: https://docs.python.org/2/library/operator.html#module-operator

>>> From operator import itemgetter >>> name_mark_age [('zhangsan', 'A', 15), ('lisi', 'B', 14 ), ('wangwu', 'A', 16), ('zhaoliu', 'B', 16)]> sorted (name_mark_age, key = itemgetter (2 )) # sort by age [('lisi', 'B', 14), ('hangsan', 'A', 15), ('hangzhou', 'A ', 16), ('zhaoliu', 'B', 16)]> sorted (name_mark_age, key = itemgetter (1, 2) # sort by level first, for the same level, see age [('hangsan', 'A', 15), ('hangwww', 'A', 16), ('lisi', 'B ', 14), ('zhaoliu', 'B', 16)]

In the official document, there is an example that is exactly the same as the above operations.

>>> Class Student: def _ init _ (self, name, grade, age): self. name = name self. grade = grade self. age = age def _ repr _ (self): return repr (self. name, self. grade, self. age) >>> student_objects = [Student ('john', 'A', 15), # note here, use class Student to generate the value Student ('Jane ',' B ', 12) in the list. # therefore, you can use student_objects [I]. age to access the age of a name, I = 0, It is john's age Student ('Dave ',' B ', 10),] >>> sorted (student_objects, key = lambda student: student. age) [('Dave ',' B ', 10), ('jar',' B ', 12), ('john', 'A', 15)]

The operator module can also be referenced to achieve the above sorting.

>>>from operator import attrgetter>>> sorted(student_objects, key=attrgetter('age'))[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>> sorted(student_objects, key=attrgetter('grade', 'age'))[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

** Conclusion: ** sorted is powerful in sorting not only, but also by specified keywords.

The preceding example is in ascending order. If reverse = True is added. For example:

>>>from operator import itemgetter >>> name_mark_age[('zhangsan', 'A', 15), ('LISI', 'B', 14), ('WANGWU', 'A', 16), ('zhaoliu', 'B', 16)]>>> sorted(name_mark_age, key=itemgetter(2),reverse=True)[('WANGWU', 'A', 16), ('zhaoliu', 'B', 16), ('zhangsan', 'A', 15), ('LISI', 'B', 14)]

Sorted Algorithm


Someone wrote an article on the Internet about the sorted Algorithm in python. In fact, by reading the official documentation, we found that sorted sorting in python is really high, using the Timsort algorithm. For details about what Timsort is, refer to the Wikipedia explanation: Explain.

Timsort is mighty in terms of time complexity.

In terms of space complexity, the overhead will increase when the amount is large.

In summary, we can see that in general, sorted is enough to meet the sorting requirements and is stable.

Of course, there are other sorting modules in python that can be used directly.

The author has a variety of articles on python sorting methods and modules on his blog and github.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.