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

Source: Internet
Author: User
Tags iterable

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

Official explanation:

ApplyFunctionOf two arguments cumulatively to the itemsIterable, 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 fromIterable. If the optionalInitializerIs present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. IfInitializerIs not given andIterableContains only one item, the first item is returned. Roughly equivalent:

That is to say: Apply an iteratable object to a method with two parameters. We call it appFun. traverse this iteratable object and use the elements in it 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 exampleReduce (lambda x, y: x + y, [1, 2, 3, 4, 5]), calculate 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, x = 1 is called for the first time according to the following code, that is, the first element, y is equal to 1, and is also the first element, 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)        except 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

So what can reduce function do and when reduce is used? Let's look at the example below:

For example, in the above example, we can 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)

Type 2: loop 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 + = tempreturn resultif _ 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+=resultreturn add(lst,temp)else:return resultif __name__=="__main__":lst = [1,2,3,4,5]print add(lst,0)

Fourth: reduce Mode

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 + yprint reduce (add, lst) # Same as method 1, just replace the lambda expression with a custom function # Or def add (x, y): return x + yprint reduce (add, lst, 0) # Same as method 2, just replace the lambda expression with a UDF.

For another example, there is a sequence set, such as [,], which counts the number of duplicates of all keys in the set, for example, 1 appears twice, and 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 methods

First: for Loop judgment

def statistics(lst):dic = {}for k in lst:if not k in dic:dic[k] = 1else:dic[k] +=1return diclst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]print(statistics(lst))

The second method: the list is de-duplicated by using the set method, and then the count method of the List is used.

def statistics2(lst):m = set(lst)dic = {}for x in m:dic[x] = lst.count(x)return diclst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]print statistics2(lst)

Third: reduce

Def statistics (dic, k): if not k in dic: dic [k] = 1 else: dic [k] + = 1 return diclst =, 3, 5, 6, 7, 7, 6, 5, 5] print reduce (statistics, lst, {}) # provides the third parameter. For the first time, the initial dictionary is empty and serves as the first parameter of statistics, then traverse the lst as the second parameter, and then use the returned dictionary set as the first parameter of the next time 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, the traversal set is used as the second parameter in turn.

The above example shows that any problem that requires operations on a set and statistical results can be solved in a loop or recursive manner, generally, reduce can be used.

The reduce function is really a good comrade "!


How can I work in English like this?

1. So it is!
2. That is the case! /That's the case!

The first sentence: so is the meaning that plays an important role, so it is advanced to the subject that it is.
The syntax structure of the entire sentence is:
Emphasize language/Object + subject (S) + Predicate (P)
The original sentence is: it is so!

The second sentence: "That" is the subject, "is the predicate, and" the "is the subject, and" case "is the object.

May you ask the case in advance?
A: no. This is a habit!

This is the case?

It turns out that

So that is what (how) it is .;
I see .;
It explains the matter .;
So that's how matters stand .;
That accounts for it.
Reference: zhidao.baidu.com/question/25488848.html? Fr = qrl3

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.