Surrounding ternary expressions, formula, generator expression

A triplet of expressions

A triplet of expressions is a simplified code python for us to provide solutions, the following syntax

res = value returned condition is satisfied if the condition else the value returned condition is not satisfied

Example:

# Original code 
DEF MAX2 (X, Y):
     IF X> Y:
         return X
     the else :
         return Y 

RES = MAX2 (1,2 ) 

# ternary expression can be solved line 
X. 1 = 
Y = 2 
RES = X IF X > the y- the else the y- # triplet of expressions to

Generative

# 1, formula list 
# all lowercase letters capitalized full 
# new_l = [name.upper () for name in L] 
# Print (new_l) 

# all removed name suffix _dsb 
# new_l = [name.replace ( '_dsb', '') for name in L] 
# Print (new_l) 

# 2, dictionary formula 
# Keys = [ 'name', 'Age', 'Gender'] 
# DIC = {Key: None for Key in Keys} 
# Print (DIC) 

# items = [( 'name', 'Egon'), ( 'Age', 18 is), ( 'Gender', 'MALE')] 
# RES = {K: V for K, V IF K items in! = 'Gender'} 
# Print (RES) 

# . 3, formula set 
# Keys = [ 'name', 'Age','gender']
# set1={key for key in keys}
# print(set1,type(set1))

Generator expressions

Is to list the formula [] to ()

# Generator expression 
# G = (I for I in Range (10) IF I>. 3) 
# ! ! ! ! ! ! ! ! ! ! ! Emphasize! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 
# Now g interior of a value not 

# Print (g, type (g)) 

# Print (g) 
# Print (Next (g)) 
# Print (Next (g)) 
# Print (Next (g)) 
# Print ( the Next (G)) 
# Print (the Next (G)) 
# Print (the Next (G)) 
# (the Next (G)) Print 

the number of characters # statistics file 
with Open ( ' notes .txt ' , the MODE = ' RT ' , encoding = ' UTF-. 8 ' ) AS F:
     # way:
    # RES = 0 
    # for Line in F: 
    #      RES + = len (Line) 
    # Print (RES) 

    # Second way: 
    # RES = SUM ([len (Line) for Line in F]) 
    # Print (RES) 

    # third approach : efficient 
    # RES = SUM ((len (Line) for in Line F)) 
    # above-can be abbreviated as follows 
    RES = SUM (len (Line) for Line in F)
     Print (RES)

 

Guess you like

Origin www.cnblogs.com/baicai37/p/12565117.html