Python-built-in function selection example

Source: Internet
Author: User
Tags iterable

See Https://www.runoob.com/python/python-built-in-functions.html official documentation for an overview https://docs.python.org/3/library/ Functions.html?highlight=built#ascii 0. Higher order functions

Satisfies two characteristics either one is the higher order function

1. The passed-in parameter of the function is a functional name

2. The return value of a function is a functional name

1. Map () function

  map(function, iterable, ... ) that is to receive two parameters, function f and an iterative object, map passes the incoming function to each element of the sequence sequentially, and returns the Iteration object map type.

Examples of usage:

NUM1 = [1, 2, 4, 7, 11]# Lambda x:x+1def Add (x):    return x+1# Lambda x:x**2def pf (x):    return x**2def map_test (fun C, Array):    num2 = [] for    i in array:        res = func (i)        num2.append (res)    return num2ret = Map_test (lambda x : x+1, NUM1) print (ret) Rett = map_test (lambda x:x**2, NUM1) print (Rett) rettt = map (lambda x:x+1, NUM1) # The first parameter is an available anonymous function or a known function, The second parameter is an iterator object, and the return value is an Iterator object print (rettt) retttt = List (rettt) print (RETTTT) name = "HelloWorld" s = List (map (lambda X:x.upper (), Name) print (s) ===============[2, 3, 5, 8, 12][1, 4,, 121]<map object at 0x00000000022faac8>[2, 3, 5, 8, 12][' H ', ' E ', ' l ', ' l ', ' o ', ' W ', ' o ', ' R ', ' l ', ' D ']
2. Filter () function

  filter(function, iterable) the filter () function receives a function f and an iterative object, the function f is to judge each element, return True or False,filter () Automatically filters out non-conforming elements based on the result of the decision, returning a new, iterative object that consists of qualifying elements.

Examples of usage:

People = [' M_ZHANGSAN_SB ', ' Lisi ', ' m_wangwu_sb ', ' Chenliu ']# Lambda x:x.endswith (' sb ') def end (n):    return N.endswith (' SB ') def filter_test (func, array):    ret = [] for    i in array:        if Func (i):            ret.append (i)    return Reta = Filter_test (lambda x:x.endswith (' sb '), people) print (a) L = List (filter (Lambda x:x.endswith (' SB '), People) print (l) ===============[' m_zhangsan_sb ', ' m_wangwu_sb ' [' m_zhangsan_sb ', ' M_WANGWU_SB ']
3. Reduce () function

The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list, and returns the final result value.

  

For example, write an F function that receives x and Y, and returns the and of X and Y:

12 deff(x, y):    return +y

When you call reduce (f, [1, 3, 5, 7, 9]) , the Reduce function calculates the following:

12345 先计算头两个元素:f(13),结果为4再把结果和第3个元素计算:f(45),结果为9再把结果和第4个元素计算:f(97),结果为16再把结果和第5个元素计算:f(169),结果为25由于没有更多的元素了,计算结束,返回结果25

The above calculation is actually a summation of all the elements of the list. Although Python has built-in sum function sum (), it is simple to sum with reduce ().

reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:

1 reduce(f, [13579], 100)

The result will change to 125 because the first round calculation is:

Computes the initial value and the first element:F (1), the result is 101.

Examples of usage:

NUM1 = [1,2,3,4]def reduce_test (func, Array, init=none):    if init = = None:        res = array.pop (0)    else:        res = i NIT    for I in array:        res = func (res, i)    return resa = Reduce_test (lambda x,y:x*y, NUM1) print (a) # Pilot inbound from Funct Ools Import reduceb = reduce (lambda x,y:x*y, NUM1, +) print (b) ============242400

4. zip () function

  zip(*iterables)

  

The ZIP function accepts any number of sequences (including 0 and 1) as parameters, returning a tuple list. The specific meaning is not good to express in words, directly look at the example:

1. Example 1:

x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = Zip (x, y, z) print xyz

The result of the operation is:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

From this result, we can see the basic operation of the ZIP function.

2. Example 2:

x = [1, 2, 3]y = [4, 5, 6, 7]xy = Zip (x, y) print xy

The result of the operation is:

[(1, 4), (2, 5), (3, 6)]

From this result, we can see how the length of the zip function is handled.

3. Example 3:

x = [1, 2, 3]x = Zip (x) print X

The result of the operation is:

[(1,), (2,), (3,)]

From this result you can see how the ZIP function works when there is only one parameter.

4. Example 4:

x = Zip () print X

The result of the operation is:

[]

From this result, you can see how the zip function works without parameters.

5. Example 5:

x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = Zip (x, y, z) u = Zip (*xyz) print U

The result of the operation is:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

It is generally thought that this is a unzip process, and its operating mechanism is this:

Before running Zip (*xyz), the value of XYZ is: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Then, Zip (*xyz) is equivalent to zip ((1, 4, 7), (2, 5, 8), (3, 6, 9))

So the result is: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

Note: Using *list/tuple in a function call means separating the list/tuple, passing it as a positional parameter to the corresponding function (provided that the corresponding function supports an indefinite number of positional parameters)

6. Example 6:

x = [1, 2, 3]r = Zip (* [x] * 3) Print R

The result of the operation is:

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

It operates in such a way that:

[x] generates a list of lists that have only one element x

[x] * 3 generates a list of lists, it has 3 elements, [x, X, X]

The meaning of Zip (* [x] * 3) is clear, zip (x, x, x)

5. Max () min () function (with sort () can be analogous)

Max (iterable, key, default) asks for the maximum value of the iterator, where iterable is the iterator, and Max will be for ... Iterate over the iterator and then pass each return value of the iterator as a parameter to the Func in Key=func (typically defined with a lambda expression), then pass the Func execution result to key and then size the key as a standard.

The following returns the maximum value according to the different judging criteria also different

D1 = {' name ': ' Egon ', ' price ': 100}d2 = {' name ': ' RDW ', ' price ': 666}d3 = {' name ': ' Zat ', ' price ': 1}l1 = [D1, d2, D3]a = Max (L1, Key=lambda x:x[' name ') print (a) b = max (L1, Key=lambda x:x[' price ') print (b)

===================
{‘name‘: ‘zat‘, ‘price‘: 1}{‘name‘: ‘rdw‘, ‘price‘: 666}
People = [    {' name ': ' Zs ', ' Age ': 1},    {' name ': ' ls ', ' Age ': 2},    {' name ': ' ww ', ' Age ': 6},    {' name ': ' cl ', ' a ' GE ': 4}]a = max (people, Key=lambda dic:dic[' age ') "Print (a) ================={' name ': ' ww ', ' Age ': 6}

  

  

Python-built-in function selection example

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.