Python ---- reduce is used in this way.

Source: Internet
Author: User

Python ---- reduce is used in this way.
Official explanation: Apply function of two 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, is the accumulated value and the right argument, y, is the update value from the iterable. if the optional initializer is present, it is placed befor E 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: It means to apply an iteratable object to a method with two parameters. We call it appFun and traverse this iteratable object, the elements are used as appFun parameters in sequence, but this function has two parameters. Which one is used as the parameter? There is such a rule. Looking at the implementation of the reduce method in the lower layer, there are three parameters. The first parameter is the appFun mentioned above, and the second parameter is the iteratable object, what about the third? If the initializer parameter is provided when the reduce method is called, the value of this parameter is used as the first parameter when appFun is called for the first time, the elements of the iteratable object are used as the second parameter of appFun. If the initializer parameter is not provided when reduce is called, when appFun is called for the first time, the first element of an iteratable object is the first element of appFun, And the iterator starts from the second element to the last one as the second parameter of appFun. Except for the first call, the first parameter of appFun is the return value of appFun. For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]) calculates the sum between 1 and 5, because the initializer parameter is not given, so when we call x + y for the first time, x = 1, that is, the first element of the list, y = 2, that is, the second element of the list, then the result of 1 + 2 is returned as x in the second call of x + y, that is, the result of the previous call, y = 2, that is, the second element, and so on, the result is 1 + 2 + 3 + 4 + 5. In this case, the following code definition is actually a problem. We call this code in the program reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]), the result is 16, and the correct result is 15. The problem is that if the set does not start with 0, then follow the code below to call x = 1 for the first time, that is, the first element, y is equal to 1, is also the first element, and the correct y should be 2. So the real reduce method should be different from the following example. Def reduce (function, iterable, initializer = None): it = iter (iterable) if initializer is None: try: initializer = next (it) wait t StopIteration: raise TypeError ('reduce () of empty sequence with no initial value ') accum_value = initializer for x in iterable: accum_value = function (accum_value, x) return accum_value what can reduce functions do, under what circumstances should we use reduce? Let's look at the following example: for example, the above example is used to accumulate an integer set. Assume that the lst is [1, 2, 3, 4, 5]. There are many ways to accumulate: first, use the sum function. Sum (lst) Method 2: cyclic mode. Def customer_sum (lst): result = 0 for x in lst: result + = x return result # Or def customer_sum (lst): result = 0 while lst: temp = lst. pop (0) result + = temp return result if _ name __= = "_ main _": lst = [1, 2, 3, 4, 5] print customer_sum (lst) third: recursive summation def add (lst, result): if lst: temp = lst. pop (0) temp + = result return add (lst, temp) else: return result if _ name __= = "_ main _": lst = [1, 2, 3, 4, 5] print add (lst, 0) Method 4: reduce (lst = [1, 2, 3, 4, 5] print reduce (lambda x, y: x + y, lst) # This method is represented as a parameter using lambda, because the third parameter of reduce is not provided, x = 1, y = 2, x = 1 + 2, y = 3, that is, the third element of the list # Or lst = [1, 2, 3, 4, 5] print reduce (lambda x, y: x + y, lst, 0) # This method uses lambda as a parameter. Because the third parameter of reduce is specified as 0, x = 0, y = 1, and x = 0 + 1 for the first execution, y = 2, that is, the second element of the list. If the third parameter of reduce is 100, x = 100 is executed for the first time, and y is still the element of the List traversal, the final result is 115 # Or def add (x, y): return x + y print reduce (add, lst) # Same as method 1, only # Or def add (x, y): return x + y print reduce (add, lst, 0) # Same as method 2, just replace the lambda expression with a UDF. For example, there is a sequence set, such as [,]. count the number of duplicates of all keys in this set, for example, 1 appears twice, 2 appears twice. The general idea is to store data in a dictionary. The element is the dictionary key and the number of occurrences is the dictionary value. There are still many first Methods: for loop to determine def statistics (lst): dic ={} for k in lst: if not k in dic: dic [k] = 1 else: dic [k] + = 1 return dic lst = [,] print (statistics (lst) Type 2: coincidentally, we first deduplicate the list using the set method, and then use the count method def statistics2 (lst): m = set (lst) dic ={} for x in m: dic [x] = lst. count (x) return dic lst = [,] print statistics2 (lst) Type 3: def statistics (dic, k ): If not k in dic: dic [k] = 1 else: dic [k] + = 1 return dic lst =, 5, 5] print reduce (statistics, lst, {}) # provides the third parameter. For the first time, the initial dictionary is empty, serves as the first parameter of statistics, and then traverses lst, as the second parameter, and then use the returned dictionary set as the first parameter or d = {} d. extend (lst) print reduce (statistics, d) # The third parameter is not provided, but the first element of the set must be a dictionary object, which is the first parameter of statistics, traversing a set in turn serves as the second parameter. Through the above example, we find that any problem that requires operations on a set and has a statistical result can be solved in a loop or recursive way, generally, reduce can be used. The reduce function is really a good comrade "!

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.