Python built-in function (--sorted)

Source: Internet
Author: User
Tags iterable

English documents:

sorted(iterable[, key][, reverse])

Return a new sorted list from the items in iterable.

has both optional arguments which must be specified as keyword arguments.

key Specifies a function of one argument that's used to extract a comparison key from each list element: key=str.lower . The default value is None (compare the elements directly).

Reverse is a Boolean value. If set True to and then the list elements is sorted as if each comparison were reversed.

Use functools.cmp_to_key() -to-Convert an old-style cmp function to a key function.

The built-in function is a guaranteed to being sorted() stable. A sort is stable if it guarantees the relative order of elements that compare equal-this are helpful for so Rting in multiple passes (for example, sort by department, then by salary grade).

Description

1. function function to sort an iterative object, returning a sorted list.

>>> A = sorted ('DCABEGF')>>> A#The returned result is a list['a','b','C','D','e','F','g']

2. The function call can provide an optional named parameter key, which is a method, the default value is None, used to specify the algorithm of the specific sorting, the function of each element of an iterative object using the key algorithm and then the order, the return is still the elements can be iterated objects.

>>> a = ['a','b','D','C','B','A']>>>a['a','b','D','C','B','A']>>> Sorted (a)#Sort by character ASCII by default['A','B','a','b','C','D']>>> sorted (A,key = str.lower)#Converted to lowercase and then sorted, ' a ' and ' a ' values, ' B ' and ' B ' values['a','A','b','B','C','D']

3. A function call can provide an optional named parameter, reverse, whose default value is False, which is used to sort the result if it is reversed.

>>> A = sorted ('DCABEGF')>>>a['a','b','C','D','e','F','g']>>> A = sorted ('DCABEGF', reverse = True)#sort results upside down>>>a['g','F','e','D','C','b','a']

Python built-in function (--sorted)

Related Article

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.