According to Liao Xuefeng python3 tutorial----python study 11th day

Source: Internet
Author: User
Tags sorts


Sorted

Sorting algorithms

The python built-in sorted () function can sort the list:

>>> sorted ([1,10,2,5,42,6]) [1, 2, 5, 6, 10, 42]

In addition, the sorted () function is also a high-order function, and he can accept a key function to implement a custom sort, for example, by absolute size:

>>> sorted ([36,5,-12,9,-21],key=abs) [5, 9,-12,-21, 36]

The function specified by key acts on each element of the list and sorts according to the result returned by the key function. Compare the original list with the list processed by Key=abs:

List = [5, -12, 9, -21]keys = [36, 5, 12, 9, 21]

The sorted() function then sorts by keys and returns the corresponding elements of the list according to the corresponding relationship:


The keys sort result = [5, 9, 12, 21, 36] |   |    |   | | Final result = [5, 9,-12,-21, 36]

Character sorting:

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' Credit ']) #根据ASCII的大小比较. [' Credits ', ' Zoo ', ' about ', ' Bob ']

Ignore case of string ordering:

>>> sorted ([' Bob ', ' about ', ' zoo ', ' credits '],key=str.lower) [' About ', ' Bob ', ' credits ', ' Zoo ']
To reverse order, you do not have to change the key function, you can pass in a third function reverse=true:
>>> sorted ([' Bob ', ' about ', ' zoo ', ' credits '],key=str.lower,reverse=true) [' Zoo ', ' credits ', ' Bob ', ' about ']


L = [(' Bob ', ', '), (' Adam ', ' the '), (' Bart ', ' the '), (' Lisa ', 88)]


Please sorted() sort the above list by name:

>>> l=[(' Bob ', ', '), (' Adam ',]>>>), (' Bart ', $), (' Lisa ', "a"), By_name (t): Return T[0].lower ()
>>> l2=sorted (l,key=by_name) >>> l2[(' Adam ', (), (' Bart '), (' Bob ', '), (' Lisa ', 88)]



Then sort by grades from highest to lowest:

>>> l=[(' Bob ', ', '), (' Adam ',]>>>), (' Bart ', $), (' Lisa ', "a"), By_score (t): Return t[1]>> > l2=sorted (l,key=by_score,reverse=true) >>> l2[(' Adam ', (), (' Lisa '), ('), ' (' Bob ', '), (' Bart ', 66)]


return function---> function as return value

Higher-order functions can also return functions as results, in addition to the ability to accept functions as parameters.

General function of summation:

>>> def calc_sum (*args): ax=0 for N in Args:ax=ax+n return ax>>> calc_sum (1,2,3,5, 4) 15

Use the function as the return value. (If you do not need to sum it immediately, but in the later code, as needed to calculate what to do?) Instead of returning the result of a sum, you can return a function that sums:)

>>> def lazy_sum (*args): def sum (): Ax=0 for N in Args:ax=ax+n return Ax return sum>>> f=lazy_sum (1,2,3,4,5) >>> f<function lazy_sum.<locals>.sum at 0x026bba08& Gt;>>> F () 15


In the example above, the function sum is defined in the function lazy_sum, and the inner function sum can refer to the arguments and local variables of the external function lazy_sum, and when Laizy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called ' Closed Package (Closure) ' program structure has great power.


When we call lazy_sum() , each call will return a new function, even if the same parameters are passed in:

>>> def lazy_sum (*args): def sum (): Ax=0 for N in Args:ax=ax+n re Turn ax return sum>>> f1=lazy_sum (1,2,3,4,5) >>> f2=lazy_sum (1,2,3,4,5) >>> f1 = F2false


The invocation results of F1 () and F2 () do not affect each other.


Closed Package

Notice that the returned function references a local variable within its definition, args so when a function returns a function, its internal local variables are referenced by the new function, so it is not easy to implement them with a simple closure.


Another problem to be aware of is that the returned function is not executed immediately, but only when it is called. f() Let's look at an example:

>>> def count (): fs=[] for I in range (1,4): Def f (): Return i*i fs.append (f) r Eturn fs>>> f1,f2,f3 = count ()

Each loop creates a new function, and then returns the 3 functions that were created.

The result of calling F1 (), F2 (), and F3 () should be 1,4,9, but actually:

>>> F1 () 9>>> F2 () 9>>> F3 () 9


The result is all 9, because the returned function refers to the variable I, but it is not executed immediately. By the time the 3 functions are returned, the variable I that they reference should become

3, so the final result is 9

One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change.

What if you must refer to a loop variable? The method is to create a function that binds the current value of the loop variable with the parameter of the function, regardless of how the loop variable is subsequently changed, the value that has been bound to the function parameter is unchanged:

>>> def Count (): Def f (j): Def g (): Return j*j return G fs=[] for I I N Range (1,4): Fs.append (f (i)) return FS
>>> f1,f2,f3=count () >>> F1 () 1>>> F2 () 4>>> F3 (9)

The disadvantage is that the code is long, and you can shorten the code with a lambda function:

>>> def Count (): Def f (j): return lambda:j*j fs = [] for I in range (1,4): Fs.appen D (f (i)) return FS
>>> f1,f2,f3=count () >>> F1 () 1>>> F2 () 4>>> F3 (9)


anonymous functions


In Python, there is a limited amount of support for anonymous functions. As an example of a map() function, when calculating f (x) =x2, in addition to defining a f(x) function, you can also pass in an anonymous function directly:

>>> list (map (lambda x:x*x,[1,2,3,4,5)) [1, 4, 9, 16, 25]

The example shows that the anonymous function lambda x:x*x is actually:

def f (x): Return x*x

The keyword lambda represents the anonymous function, and the x preceding the colon represents the function parameter

The anonymous function has a limit, that is, there can be only one expression, no return, the value of the expression is return

There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. In addition The anonymous function is also a function object, or you can assign the anonymous function to a variable, and then use the variable to invoke the function:

>>> F=lambda x:x*x>>> f<function <lambda> at 0x02c9fd68>>>> F (5) 25

The anonymous function can also be used as the return value of the function:

def bulid (x, y): return lambda:x*x + y*y


This article is from the "Creative Pilgrim" blog, so be sure to keep this source http://dearch.blog.51cto.com/10423918/1762147

According to Liao Xuefeng python3 tutorial----python study 11th day

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.