Python's reduce,map, selfie,

Source: Internet
Author: User
Tags iterable

One, reduce (function,iterable), it is the same form as the map () function. However, the parameter function must have two parameters .

The reduce () function is a cumulative calculation of the result continuation and the next element of the sequence.

Cases

>>>def Add (x, y): # Two number added
... return x + y
...
>>> reduce (add, [1,2,3,4,5]) # calculation list and: 1+2+3+4+5
15
>>> reduce (lambda x, Y:x+y, [1,2,3,4,5]) # using lambda anonymous functions
15




Twomap (function,iterable)is to use each element in the list for a function.

1. Return value:

Python 2.x returns a list.

Python 3.x returns an iterator.
so there are two basic ways to get a map return value in Python3:
①print (Map (f,iter)) #这里的f代表函数, Iter represents an iterative object.
② uses a For loop.


Cases
①m = map (lambda x:x + 1, [1, 2, 3])
Print (list (m)) #结果为: [5, 7, 9]

② provides two lists to add the list data to the same location
>>> map (lambda x, y:x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]




Three zip The function accepts any number of iterated objects as arguments, packages the corresponding elements in the object into a tuple, and returns an iterator to the Zip object.
Cases
LT1 = [' A ', ' B ', ' C ']
LT2 = [1, 2, 3]
LT3 = [' A ', ' B ', ' C ']
result = List (Zip (LT1, LT2, LT3))
Print (Result) #输出结果: [(' A ', 1, ' a '), (' B ', 2, ' B '), (' C ', 3, ' C ')]



Fourfilter ()The function is used to filter the sequence, filter out elements that do not meet the criteria, and return a new list of eligible elements.
Filter receives two parameters, the first is a function, the second is a sequence, each element of the sequence is passed as a parameter to the function, and then returns True or False, and finally the element that returns true is placed in the new list.
Grammar:Filter (function, iterableble)

Cases
func = lambda x:x% 2 = = 1
Print (List (func, [i])) #输出结果: [1, 3]

Python's reduce,map, selfie,

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.