Map (), zip () function, and expression lambda usage in Python

Source: Internet
Author: User
anonymous function Lambda usage

Use lambda in Python to create anonymous functions. A lambda is just an expression that has its own namespace and cannot access parameters outside of the free argument list or in the global namespace.

Lambda syntax

Lambda arg1,arg2 ...: expression

Lambda Expressions act as a function of sketching. Example:

>>> sum = lambda x,y:x+y
>>> sum (2,4)
6
Zip () function usage

A zip () is a built-in function of Python that accepts a series of objects that can be iterated as arguments. Packages the corresponding elements in the object into a tuple and returns a list in Python2. Returns an object that supports traversal in Python3.
If the length of the incoming argument is unequal, the length of the list is returned and the object with the shortest length in the parameter is the same. Use the * operation symbol, you can extract the list unzip.

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=[1,2,3,4,5,6]
>>> list (Zip (a,b))  #转换为List列表
[(1, 4), (2, 5), (3, 6)]
>>> list (Zip (a,c))  #返回list长度是参数中长度最短的对象的长度
[(1, 1), (2, 2), (3, 3)]
>>> d=zip (a,b)
>>> list (Zip (*d)) 
[(1, 2, 3), (4, 5, 6)]

The list (Zip ()) can only be invoked once, otherwise it returns []. To view the source code for the Python3 Supply zip (), zip () is actually a generator object, so using list () to get the zip () result is equivalent to completing an iterative traversal, the second time using the list () when the iteration has ended, so return []. map () function usage

Map () maps the specified sequence based on the function provided. The first parameter function calls the function function with each element in the parameter sequence, and returns a new list that contains the return value of each of the function functions.

The syntax is:

Map (function,iterable,...)

An example of using the map () function.
>>> A=map (Lambda x:x*2, Range (4))
>>> list (a)
[0, 2, 4, 6]

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.