Home  >  Article  >  Backend Development  >  Introduction to the use of Pythont special syntax filter, map, reduce, apply

Introduction to the use of Pythont special syntax filter, map, reduce, apply

高洛峰
高洛峰Original
2017-03-07 16:26:391520browse

(1)lambda

lambda is a very useful syntax in Python, which allows you to quickly define a single-line minimal function. Similar to macros in C language, they can be used wherever a function is required.

The basic syntax is as follows:

Function name = lambda args1,args2,...,argsn : expression

For example:

add = lambda x,y : x + y
print add(1,2)

(2) filter

The filter function is equivalent to a filter. The function prototype is: filter(function, sequence), which means sequence sequence Each element in the sequence executes the function in turn. The function here is a bool function. For example:

sequence = [1,2,3,4,5,6,7,8,9,10]
fun = lambda x : x % 2 == 0
seq = filter(fun,sequence)
print seq

The following code means to filter out the elements in the sequence. All even numbers.

The filter function prototype is roughly as follows:

def filter(fun,seq):
    filter_seq = []
    for item in seq:
        if fun(item):
            filter_seq.append(item)
    return filter_seq

(3) map

The basic form of map is: map(function, sequence), which applies the function function to the sequence sequence and then returns a final result sequence. For example:

seq = [1,2,3,4,5,6]
fun = lambda x : x << 2

print map(fun,seq)

The function source code of map is roughly as follows:

def map(fun,seq):
    mapped_seq = []
    for item in seq:
        mapped_seq.append(fun(item))
    return mapped_seq

(4)reduce

The form of the reduce function is: reduce(function, sequence, initVal), function represents a binary function, sequence represents the sequence to be processed, and initVal represents processing initial value. For example:

seq = [1,2,3,4,5,6,7,8,9,10]
fun = lambda x,y: x + y

print reduce(fun,seq,0)

means accumulating each element in the sequence seq starting from the initial value 0, so the result is 55

## The source code of the #reduce function is roughly as follows:


def reduce(fun,seq,initVal = None):
    Lseq = list(seq)
    if initVal is None:
        res = Lseq.pop(0)
    else:
        res = initVal
    for item in Lseq:
        res = fun(seq,item)
    return res

(5) apply

apply is used To indirectly replace a function, such as:


def say(a,b):
    print a,b

apply(say,(234,&#39;Hello World!&#39;))

For more Pythont special syntax filter, map, reduce, apply usage instructions, please pay attention to the PHP Chinese website for related articles!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn