With old Ziko Python's big topic small function (2)

Source: Internet
Author: User
Tags iterable mul
The title of the last and this lecture is "Big topic small function", so-called big topic, that is, if these functions are traced, they will find something that sounds taller. This way of thinking absolutely I firmly inherited the fine tradition of the Chinese nation. Since the people of China saw the British began to play football, and until now the so-called an erection, has been trying to argue that the football originated in the former former dynasty of a certain country era, and also moved out of the time of a star called High Qiu to argue, of course, the erection of a country is unable to stop the national team in the World Cup, can only use Gao Lai to fantasize about. This way of thinking, I was firmly inherited, because in the course of my growth, it has been served as a fine tradition. Ah Q was originally surnamed Zhao, and Zhao Master is a family, than the scholar to long three generation, although Zhao master hit the mouth.

Less nonsense, the book to the previous text, has studied the map, the following see reduce.

I can't help but get some crap. Do not know crossing have heard Mapreduc, if not, then Hadoop? If not, just Google. Here's what I've copied from Wikipedia to share.

The code is as follows:


MapReduce is a software architecture proposed by Google for parallel operations in large-scale datasets (larger than 1TB). Concepts such as "map" and "Reduce", and their main ideas, are borrowed from functional programming languages and are borrowed from vector programming languages.

Do not care is not understand, in short, you can use the idea of the beginning of a fantasy, the original today to tinker this reduce also with big data about AH. In any case, you have a dream of the general feeling on the line.

Reduce

Back to reality, sober up, continue to tap the code:

The code is as follows:


>>> reduce (lambda x,y:x+y,[1,2,3,4,5])
15

Please crossing careful observation, can you see how it is calculated? Draw a diagram:

Remember how the map was calculated? Forgot? Look at the code:

The code is as follows:


>>> List1 = [1,2,3,4,5,6,7,8,9]
>>> list2 = [9,8,7,6,5,4,3,2,1]
>>> map (Lambda x,y:x+y, list1,list2)
[10, 10, 10, 10, 10, 10, 10, 10, 10]

Crossing contrast, you know the difference between the two. The original map is the upper and lower operations, reduce is a cross-element operation.

The authoritative explanation comes from the official website:

The code is as follows:


Reduce (function, iterable[, initializer])

Apply function of arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to A single value. For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates (((((1+2) +3) +4) +5). The left argument, X, are the accumulated value and the right argument, y, are the update value from the iterable. If the optional initializer is present, it's placed before the items of the iterable in the calculation, and serves as a Default when the iterable is empty. If initializer is not given and Iterable contains only one item, the first item is returned. Roughly equivalent to:

The code is as follows:


def reduce (function, iterable, Initializer=none):
it = iter (iterable)
If initializer is None:
Try
initializer = next (IT)
Except stopiteration:
Raise TypeError (' reduce () of empty sequence with no initial value ')
Accum_value = initializer
For x in it:
Accum_value = function (Accum_value, x)
Return Accum_value

If we use the familiar for loop to do the above reduce, we can do this:

The code is as follows:


>>> LST = range (1,6)
>>> LST
[1, 2, 3, 4, 5]
>>> r = 0
>>> for I in range (len (LST)):
... r + = Lst[i]
...
>>> R
15

For universal, reduce is concise.

In order to exercise thinking, to see such a problem, there are two list,a = [3,9,8,5,2],b=[1,4,9,2,6], calculated: a[0]b[0]+a1b1+ ... The result.

The code is as follows:


>>> A
[3, 9, 8, 5, 2]
>>> b
[1, 4, 9, 2, 6]

>>> Zip (A, b) #复习一下zip, use the following method
[(3, 1), (9, 4), (8, 9), (5, 2), (2, 6)]

>>> sum (x*y for x, y in Zip (A, b)) #解析后直接求和
133

>>> new_list = [x*y for x, y in Zip (A, b)] #可以看做是上面方法的分布实施
>>> #这样解析也可以: new_tuple = (x*y for x, y in Zip (A, b))
>>> new_list
[3, 36, 72, 10, 12]
>>> sum (new_list) #或者: sum (new_tuple)
133

>>> reduce (lambda sum, (x, y): Sum+x*y,zip (A, B), 0) #这个方法是在耍酷呢吗?
133

>>> from operator import Add,mul #耍酷的方法也不止一个
>>> Reduce (Add,map (mul,a,b))
133

>>> reduce (lambda x,y:x+y, map (Lambda X,y:x*y, A, b)) #map, Reduce,lambda are all complete and cool?
133

Filter

The Chinese meaning of filter is "filter", in Python, it is the role of the filter. First look at the official note:

The code is as follows:


Filter (function, iterable)

Construct a list from those elements of iterable for which function returns TRUE. Iterable May is either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also have that type; Otherwise it is always a list. If function is a None, the identity function is assumed, which is, and all elements of iterable that is false is removed.

Note that the filter (function, iterable) is equivalent to [item for item ' in Iterable if function (item)] If function was not Non E and [item for item in Iterable if Item] if function is None.

This time I really do not translate (as if there has been no translation), but also do not explain the main points. Please yours faithfully be sure to read the above text yourself and understand its meaning. English, no matter how the emphasis is not excessive, even to do beggars, say two English, may also be able to get the pound of dollars.

It is realized by the following code:

The code is as follows:


>>> numbers = range ( -5,5)
>>> numbers
[-5,-4,-3,-2,-1, 0, 1, 2, 3, 4]

>>> filter (lambda x:x>0, numbers)
[1, 2, 3, 4]

>>> [x for X in numbers if x>0] #与上面那句等效
[1, 2, 3, 4]

>>> filter (lambda c:c!= ' i ', ' Qiwsir ') #能不能对应上面文档说明那句话呢?
' QWSR ' # "If iterable is a string or a tuple, the result also have that type;"

At this point, with two of these introduced a few small functions, these functions in the performance of the program to improve, there is no significant or stable expectations, but in the code of simplicity, is obvious to all. Sometimes it can be used to show off the elegance of Python and play it cool.

  • 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.