Introduction to common built-in functions in Python (filter,map,reduce,apply,zip)

Source: Internet
Author: User

Python is a very concise, elegant language, a lot of built-in functions to use, you can use very little code to implement a lot of complex functions, if the same function to let C/c++/java to implement, may be large, in fact, Python is a complex data structure hidden in the built-in function , as long as you write your own business logic, Python will automatically come up with the results you want. The built-in functions include, filter,map,reduce,apply, anonymous functions, list parsing, and more powerful functions. The most obvious benefits of using built-in functions are:

1. Fast, using built-in functions, more than normal Python implementation, the speed is about one times faster. Equivalent to the speed of C + +

2. Simple code


Filter

Grammar:

>>> Help (filter) to built-in function filter in Module __builtin__:filter (...)    Filter (function or None, sequence), list, tuple, or string    Return those items of sequence for which function (item ) is true.  If    function is None, and return the items is true.  If sequence is a tuple    or string, return the same type, else return a list.

Use:

Used to filter values that do not match the function func (), similar to SQL in select value! = ' a '

Equivalent to an iterator that invokes a Boolean function, Func, to iterate over each element in the SEQ, returning a sequence that Bool_seq returns to True

>>> First parameter: function or none, functions or none

>>> second parameter: sequence, sequence

Description

>>> If the first argument is a function, then the return condition is a true sequence (list, progenitor, or string)

>>> If the first argument is none, then return all items in the sequence that are true

Example 1: To filter out all lists that have a value of false

Print filter (none,[-2,0,2, ', {}, ()])     #输出 [ -2,2], the rest is false

Example 2: To filter a letter

>>> filter (lambda x:x! = ' A ', ' ABCD ')

' BCD '

Example 3: Filter the names of people whose letters begin with B

>>> names = [' Alice ', ' Bob ', ' Smith ', ' David ', ' Barbana ']
>>> Filter (Lambda x:x.startswith (' B '), names)
[' Bob ', ' Barbana ']

Example 4: To filter the odd and even items in the FIB list

>>> fib = [0,1,1,2,3,5,8,13,21]
>>> filter (lambda x:x%2,fib) #实际上等同于x%2 = = 1
[1, 1, 3, 5, 13, 21]
>>> filter (lambda x:x%2 ==0,fib)
[0, 2, 8]

Example 5: To get all 2-20 of the mass sequence out

>>> filter (lambda x:not [x%i for I in range (2,x) if x%i = = 0],range (2,20))
[2, 3, 5, 7, 11, 13, 17, 19]

Example 6: To filter all sub-lists, the word is ' Python '.

def filter_word (word):  try:    return word! = ' Python '  except ValueError:    return falsewords = [[' Perl ', ' Python ', ' Shell '],[' Java ', ' C + + '],[' VB ', ' Dephi ']]print [Filter (Filter_word,word) for word in words] #用了列表解析的方法

The logical implementation of filter:

def filter (FUNC,SEQ):    f_seq = []                  #建一个空序列, used to store filtered elements for    item in SEQ:            #对序列中的每个元素进行迭代        if func (item) :          #如果为真的话            f_seq.append (item)  #满足条件者, add the    return f_seq                #返回过滤后的元素print filter (lambda x:x> 0,[- 2,0, 2]) #对匿名函数进行过滤, return positive >>>[2]
Map:
>>> Help (map) to built-in function map in module __builtin__:map (...)    Map (function, sequence[, sequence, ...]) List    Return A list of the results of applying the function to the items Of the    argument sequence (s).  If more than one sequence are given, the    function is called with an argument list consisting of the corresponding    I TEM of each sequence, substituting None for missing values when not all    sequences has the same length.  If the function is None, return a list of the items of the    sequence (or a list of tuples if more than one sequence).
use:

>>> performs the same operation on one or more sequences, returning a list

Description

1. Returns a list that is the result set of parameter func for SEQ1,SEQ2 processing

2. You can have multiple sequences, and if the function is None, return a list of sequences

Example 1: General usage

>>> map (Lambda x:x+1,[1,2,3,4])
[2, 3, 4, 5]
>>> map (Lambda x,y:x+y,[1,2,3,4], (10,20,30,40))
[11, 22, 33, 44]
>>> Map (Lambda x,y:x+y if y else x+10,[1,2,3,4,5], (1,2,3,4))

#第一个序列中的第五个元素存在, but does not exist in the second sequence, so y is false, so execute 5+10
[2, 4, 6, 8, 14]
>>> map (none,[1,2,3,4,5], ()) #如果是None的话, with None to fill the vacancy caused by the short sequence
[(1, 1), (2, 2), (3, none), (4, none), (5, none)]

>>> names = [' Alice ', ' Jerry ', ' Bob ', ' Barbar ']
>>> map (len,names) #求列表中每个元素的长度
[5, 5, 3, 6]

Example 2: Ask for a number between 0-5, [itself, squared, cubic], such as: element 2, then return: [2,4,8]

def func1 (x): return x                   #返回自身def func2 (x): Return x * * 2              #返回平方def func3 (x): Return x * * 3              #返回立方funcs = [func1,f UNC2,FUNC3]              #函数列表for i in range (5):                       #遍历列表    Print map (lambda func:func (i), Funcs) #对其中每个元素执行func1 (i), Func2 ( i), func3 (i) operation
Example 3: Implementing the following logical Structure

1.0 [1,2,3,4,5]

2.0 [1,2,3,4,5]

....

Foos = [1.0,2.0,3.0,4.0,5.0]bars = [1,2,3,4,5]def Test (foo):    print Foo,barsprint map (test,foos)
The implementation logic of map
def map (func,seq):    map_seq = []                      #建空序列 for    item in SEQ:                  #对序列中每个元素进行处理        map_seq.append (func (item))    #往空序列中添加func处理过的元素    return map_seq                    #返回最后的列表print map (Lambda x:x * 2,[1,2,3,4])  #[2,4,6,8]
Reduce:

Use:

Func is a two-tuple function that functions func on the elements of a SEQ sequence, each carrying a pair (the previous result and the element of the next sequence), continuously acting on the resulting subsequent result with the existing result and the next value, and finally reducing our sequence to a single return value: If the initial value of Init is given, The first comparison will be init and the first sequence element instead of the sequence's first two elements.

Description

>>> Help (reduce)-on built-in function, reduce in module __builtin__:reduce (...)    Reduce (function, sequence[, initial]), value    Apply a function of the of the arguments cumulatively to the items of a SEQ Uence, from left    to right, so as to reduce the sequence to a single value.    For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates (((((    1+2) +3) +4) +5).  If Initial is present, it's placed before the items    of the sequence in the calculation, and serves as a default when The    sequence is empty.

Example:

>>> reduce (lambda x,y:x+y, [47,11,42,13])
113

The implementation process is as follows:


The logical implementation of reduce:

def reduce (func,seq,init=none):    l_seq = list (seq)                  #先转为列表    if Init is None:                   #如果初始值        res = l_seq.pop (0    else:        res = init    for item in L_SEQ:        res = func (res,item)           #func (Res,item) passed as result set to res    return Res                         #返回结果集print reduce (lambda x,y:x+y,[1,2,3,4]) #结果为10print reduce (lambda x,y:x+y,[1,2,3,4],10)     #结果为20, Init initial value is 10
Apply:

Grammar:

>>> Help (apply) to built-in function apply in module __builtin__:apply (...)    Apply (object[, args[, Kwargs]), value call    a callable object with positional arguments taken from the tuple args , and    keyword arguments taken from the optional dictionary Kwargs.    Note that classes is callable, as is instances with a __call__ () method    Deprecated since release 2.3. Instead, use the extended call Syntax:        function (*args, **keywords).

Use:

>>> when a function parameter exists in a tuple or a dictionary, it is used to indirectly invoke the function, and the arguments in the tuple or dictionary are passed in order.

Description

1. Args is a tuple containing positional parameters passed according to the parameters required by the function, and if Func (a=1,b=2), then the tuple must be passed strictly in the order of the position of the parameter (a=3,b=4), not the order of (B=4,a=3)

2. Kwargs is a dictionary that contains keyword parameters, where args, if not passed, Kwargs need to be passed, must be left blank in the location of args

3. The return value of the Apply function is the return value of the Func function.

Example 1: General use

Def func1 ():               #无参函数  print ' No args! ' def func2 (arg1,arg2):      #两个参数  print arg1,arg2def func3 (arg1=1,arg2=2):  #带字典函数  Print arg1,arg2if __ name__== ' __main__ ':  apply (FUNC1)  apply (Func2, (' Hello ', ' world! '))  Apply (func3, (), {' arg1 ': ' This was param1 ', ' arg2 ': ' This is Param2 '})  #注意元祖参数为 ()

Zip

>>> Help (Zip) to built-in function zip in module __builtin__:zip (...)    Zip (seq1 [, SEQ2 [...]]), [(Seq1[0], seq2[0] ...), (...)    Return a list of tuples, where each tuple contains the i-th element from each of the    argument sequences.  The returned list is truncated in length to the length of the    shortest argument sequence.
use:

>>> returns a list of meta-ancestors that contains the corresponding elements of each sequence in order, whichever is the smallest one

Description

>>> this built-in function is actually better understood, the object returned is a list of meta-ancestors, to see the example is good to understand

Example:

>>> Zip (Range (5), Range (1,20,2))
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)]
>>> x= (a); y= (4,5); z= (6,)
>>> zip (x, y, z)
[(1, 4, 6)]


You can see this comprehensive example:

Http://www.360doc.com/content/14/0507/11/7821691_375450523.shtml

http://my.oschina.net/cloudcoder/blog/226461


Introduction to common built-in functions in Python (filter,map,reduce,apply,zip)

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.