Concise python Tutorial--c++ Programmer's Perspective (ix): Functional programming, special class methods, testing, and others

Source: Internet
Author: User
Tags generator iterable

Functional Programming Lambda

Exec,eval and ASSERT statements, repr functions

Lambda statement

Used to create a short single-line anonymous function

Namevaluestr(value)
Equivalent to
Print_assign(namevalue):
    STR(value)  

Lambda requires a parameter, followed only by a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even the print statement cannot be used in lambda form, only expressions are used.

>>> Ftwice = Lambda s:s*2
>>> Ftwice (2)
4

Again, as the Make_repeater function creates a new function object at run time, and returns it.

Yield expression

Similar to iterators, generators allow processing of data sequences

The difference is that the generator uses the YI?E?L?D expression to minimize the memory consumed by the program and to provide an iterator-like capability on a large-scale data set.

Map () function
From Itera,iterb ... To remove the corresponding element in the application map

Map (f, Itera, iterb, ...)

Built-in functions often used with iterators.

Returns a list containing F (itera[0], iterb[0]), F (itera[1] , iterb[1]), F (itera[2], iterb[2]), ....

map(f, iterable)基本上等于[f(x) for in iterable]

But in a plural case different:


>>> List1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]

Map () only does the in-column operation
>>> def ABC (A, B, c):
... return a*10000 + b*100 + C
...

>>> Map (ABC,LIST1,LIST2,LIST3)
[114477, 225588, 336699]

The list parsing does is the Cartesian product

>>> [ABC (A,B,C) for a in List1 for B in List2 for C in List3]

[114477, 114488, 114499, 115577, 115588, 115599, 116677, 116688, 116699, 224477, 224488, 224499, 225577, 225588, 225599, 2 26677, 226688, 226699, 334477, 334488, 334499, 335577, 335588, 335599, 336677, 336688, 336699]

Equivalent to

result = []

For a in List1:
For B in List2:
For C in List3:
Result.append (ABC (ABC))

Filter () function

(can be overridden by list)

  
Select elements from ITER that satisfy the predicate condition
 filter ( Predicate, iter)      
 Returns a list that contains all the Sequence elements that meet a certain condition 
  form very concise 
Existing_files = Span class= "NB" >filter (os. Path. Existsfile_list)
   
reduce () function
  For each element in ITER 22, use func  
 reduce (Func, iter,  [initial_value]) 

func  must is a function that takes Elements and returns a single value. 
 
First count Init=func ( Initial_value,a) func (Init,b) and func (func (init, < Span class= "pre" >b),  c) ...



Sorted () function
Sorted (iterable, [Cmp=none], [Key=none], [Reverse=false])   
Reference http://wiki.python.org/moin/HowTo/Sorting
Any () and all () functions
Any () returns true if any element in the iterable is a true value

All () returns true if all of the elements is true values
 >>> any ([1,< Span class= "Mi" >1,1]) true >>> all ([0,1 ,0]) false       
Generator expressions
The syntax is slightly different from the list comprehensions
(Expression for expr1 in Sequence1             if Condition1             ... For ExprN in Sequencen             if conditionn)

Output:the successive values of expression

Obj_total = sum(obj. Count for obj in list_all_objects())

Generators
Functions that simplify the task of writing iterators, which

Functools.  Partial()  

Partial function Application
EXEC statement Used to execute a python statement stored in a string or file.

For example, you can generate a string that contains Python code at run time, and then execute the statements using the EXEC statement.

>>> exec ' print ' Hello world '
Hello World

Eval statement Used to calculate a valid python expression stored in a string.

>>> eval (' 2*3 ')
6

Assert statement Used to declare a condition to be true.
When an Assert statement fails, a assertionerror is raised.
repr function The canonical string representation used to get the object.
The inverse quotation marks (also known as converters) can accomplish the same function.
Note that most of the time there is an eval (repr (object)) = = object.

>>> i = [' Item ']
>>> ' I '
"[' Item ']"
>>> repr (i)
"[' Item ']"

function modifiers Adjust the behavior of an existing function by intervening the start and close mechanism of the function

Special methods for classes

__init__ (self,...)

Called before the new object is to be returned for use.

__del__ (self)

Called exactly before the object is to be deleted.

__str__ (self)

Called when the object is using the PRINT statement or using STR ().

__lt__ (Self,other)

Called when the less-than operator (<) is used. Similarly, there are special methods for all operators (+,>, and so on).

__getitem__ (Self,key)

Called when using the X[key] index operator.

__len__ (self)

Called when using the built-in Len () function on a Sequence object.

Test

For larger programs, the test framework is essential.

In the standard library, the UnitTest module is based on the popular Xunit testing framework. Doctest allows input from a shell session.

Reference:

A brief analysis of the map () function in Python

Http://docs.python.org/2/howto/functional.html

Python Special Syntax: filter, map, reduce, lambda, yield

Http://www.dataguru.cn/blog-10716-1133.html

http://jgy3.ggclk.com/url?url=http%3A%2F%2Fmikecvet.wordpress.com%2F2010%2F07%2F02% 2fparallel-mapreduce-in-python%2f&v=4&i=6&q=map%20python%20lambda%20%20yield%20reduce%20filter &p=0&tr=0&at=0&ar=0&ab=0&mr=0&ir=0&kgr=0&nr=0&iar=0&sr=0

From:http://www.cnblogs.com/wei-li/p/3439182.html

Concise python Tutorial--c++ Programmer's Perspective (ix): Functional programming, special class methods, testing, and others

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.