Python Grammar Tips

Source: Internet
Author: User

1, three-dimensional expression:

Value= true-expr If condition else false-expr

Example: a= ' positive ' if 3>0 else ' negative '

2. Use list derivation to replace map and filter

a=[1,2,3,4,5]squares=list (Map (LambdaX:x**2, a))Print(squares)#[1, 4, 9, +,]Squares=[x**2 forXinchA]Print(squares)#[1, 4, 9, +,]Data=list (Map (LambdaX:x**2, Filter (Lambdax:x%2==0,a )))Print(data)#[4, +]Data_one=[x**2 forXinchAifx%2==0] equivalent todata_one=[x**2 for X in A and x%2==0]
Print(Data_one)#[4, +] #dictionaries and collections have similar derivation mechanisms.chile_ranks={'Ghost': 1,'Habanero': 2,'Cayenne': 3} rank_dict={rank:name forName,rankinchchile_ranks.items ()} Chile_len_set={len (name) forNameinchrank_dict.values ()}Print(rank_dict)#{1: ' Ghost ', 2: ' Habanero ', 3: ' Cayenne '} Print(Chile_len_set)#{8, 5, 7}

3. Function-Type programming

Functions that can receive other functions as arguments are called higher order functions (High-order function).

Representative higher-order functions: Map () filter () and reduce ()

The map () function receives two parameters, one is the function, and the other is the ITERABLE,MAP functions the incoming function to each element of the sequence sequentially.

and return the result as a new iterable.

 lambda_sum=lambda  x,y:x+y  print  (Lambda_sum (3,4))  #  7  data_list=[1,3,5,6]result  =map (lambda  x:x+3,data_list)  print  (list (result)) #  [4, 6, 8, 9]  def   f (x):  return  x+3result_one  =list (map (f,data_list))  print    (Result_one) #  [4, 6, 8, 9]   

Reduce (): Action of a function in a sequence [x1,x2,x3,...] , the function must receive two parameters, reduce results

Continue with the next element of the sequence to do the cumulative calculation. It doesn't feel very useful! Can write yourself, will be troublesome, if necessary, still available.

 fromFunctoolsImportreducedata_list=[1,3,5]Print(Reduce (LambdaX,y:2*x+y,data_list))# thedeff_reduce (x, y):return2*x+yPrint(Reduce (f_reduce,data_list))# theNew_list=data_list[:1] forIinchRange (1, Len (data_list)): New_list.append (2*new_list[i-1]+Data_list[i])Print(new_list)#[1, 5, the]Print(New_list[-1])# thedefprod (L): New_list=l[:1]     forIinchRange (1, Len (L)): New_list.append (New_list[i-1]*L[i])returnNew_list[-1]Print(Prod ([3, 5, 7, 9]))#945defprod (L):returnReduceLambdax,y:x*y,l)Print(Prod ([3, 5, 7, 9]))#945

3, filter (), and map () similar, also receive a function and a sequence. Unlike map (), filter () applies the incoming function to each element sequentially,

The element is then persisted or discarded based on whether the return value is TRUE or False

List (filter (lambda x:x%2==0,[3,4,5))  #[4]list (filter (lambda x:x%2==1, [3,4,5]))  # [3,5]
Lst=[x**2 forXinchRange (10)]#[0, 1, 4, 9, +,-x1=[1,3,5]y1=[9,12,13]lst1=[x**2 for(x, Y)inchZip (x1,y1)ifY>10]Print(LST1)#[9]Dict={k:v forKvinchEnumerate ('Vamei')ifV not inch 'VI'}Print(dict)#{1: ' A ', 2: ' m ', 3: ' E '}

Python Grammar Tips

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.