Python's eval function, map function, zip function

Source: Internet
Author: User

The eval (str) function is powerful, as the official explanation is that the string STR is evaluated as a valid expression and returns the result of the calculation. So it's good to combine math as a calculator.

The most common functions of the eval () function are:
1. Evaluates a valid expression in a string and returns the result

>>> eval(‘pow(2,2)‘)4>>> eval(‘2 + 2‘)4>>> eval("n + 4")85

2. Convert the string to the corresponding object (such as the conversion between list, tuple, dict, and string)

>>> A =[[Up], [3,4], [5,6], [7,8], [9,0]] ">>> B = eval (a)>>> b[[1,2], [3,4], [5,6], [7,8], [9,0]]>>> A ="{1: ' xx ', 2: ' yy '}">>> C = eval (a)>>> c{1: ' xx ', 2: ' yy '}>>> a = "(1,2,3,4)">>> d = eval (a) C16>>>> d (1, 2, 3, 4)          

3. Convert the string back to the object using the anti-quote conversion

>>> List1 = [1,2,3,4,5]>>>' List1 '' [1, 2, 3, 4, 5] '>>> Type ( ' List1 ') <type   ' str ' >>>> type (eval ( ' List1 ')) <type   ' list ' >>>> a = eval ( ' List1 ') >> > A[1,  2, 3, < Span class= "Hljs-number" >4, 5]      

The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.

For example, we have a function f (x) =x%2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to achieve

#使用lambda函数

>>> Print map (lambda x:x% 2, range (7))

[0, 1, 0, 1, 0, 1, 0]

One of the simplest examples, such as an F (x) = X2,map () action on List [1, 2, 3, 4, 5, 6, 7, 8, 9] results in the following: The returned result is still list

Previously used zip , only used the simplest, combined two lists, did not dig carefully, and later in the experiment Building experiment, encountered such a line of code:

for row in zip(*field)]     #field 是一个矩阵
Basic use of zip ()

First Look at help(zip) :

HelpOn built-Inchfunction zipInchModule __builtin__:zip (...) zip (seq1 [, SEQ2 [...]]), [(seq1[0], seq2[0] ...), (...) return a list of tuples, where each tuple contains the i-th  Element from each of the argument sequences. The returned list is truncated Span class= "Hljs-keyword" >in length to the length of the shortest Argument sequence. none          

The effect is:

Definition: Zip ([seql, ...]) Accepts a series of iterative objects as parameters, packages the corresponding elements in the object into tuple (tuples), and then returns a list of these tuples (lists). If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter.

The popular point is to make a few lists (0 or 1 or more) corresponding to the location of the elements of the new tuple , these new tuple composition of one list .
Use a few examples directly to illustrate:

Example
x = [1,2,3]y = [4,5,6]z = [7,8,9]XYZ = Zip (x, y, z)Print xyz"' The result is: ' [(1,4,7), (2,5,8), (3,6,9)]#对应元素组成一个新的元组, tuple constituent list#---------------------------------------##无参数时, x = Zip ()Print X#结果是: []#---------------------------------------##长度不等时, take the minimum x = [1,2, 3]y = [' A ', ' B ', ' C ', ' d ']xy = Zip (x, y)print xy#结果是: [(1, ' a '), (2, 
                                                                                  
                                                                                    ' B '), (
                                                                                   3, ' C ')]  
                                                                                            
Common methods
#可变参数传递的使用 (very often a use), this can be used to transpose the Matrix o~ as follows: Experiment#楼的那代码就是转置矩阵x = [[1,2,3], [4,5,6], [7,8,9]]y = Zip (*x) print y #结果是: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] #转置就是:             
map (list, y)#This is often used in this way: compression and decompressionx= [1, 2, 3]y= [4, 5, 6]z= [7, 8, 9]xyz= Zip (x, y, z) res = ZIP (*xyz)PrintRes#The results are conceivable, after compression in the decompression:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]" " " #There is also the structure of the dictionary is often used:x= ['a','b','C']y= ['x','y','Z']z=zip (x, y) d=Dict (z)PrintD#The result is:{'a':'x','C':'Z','b':'y'}" " "#------------------------------##combined with ITER:a= [1, 2, 3, 4, 5, 6]b= Zip (* ([ITER (a)] * 2))Printb#The result is:[(1, 2), (3, 4), (5, 6)]

Python's eval function, map function, zip function

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.