Ternary expressions with Python, derivation type list, generator expression

1. a triplet of expressions

INPUT = name ( " Name >>: ' )
res='SB' if name == 'aaaa' else 'NB'
print(res)

2. List comprehensions

#1、示例
egg_list=[]
for i in range(10):
    egg_list.append ( ' eggs S% ' % I)

egg_list=['鸡蛋%s' %i for i in range(10)]

#2、语法
[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
Similar to
res=[]
for item1 in iterable1:
    if condition1:
        for item2 in iterable2:
            if condition2
                ...
                for itemN in iterableN:
                    if conditionN:
                        res.append(expression)

# 3, Advantages: easy to change the programming practice, to be called declarative programming

3. The generator expression

# 1, the list of the derived formula [] with () is the generator expression

# 2, Example: raw egg into a basket to your old hen, when used on eggs, which is characteristic generator 
>>> Chicken = ( ' eggs S% ' % I for I in Range (. 5 ) )
 >>> Chicken
 <Object Generator <genexpr> AT 0x10143f200>
>>> Next (chicken)
 ' eggs 0 ' 
>>> List (chicken) # due to chicken may be iterative, and thus can be converted into a list 
[ ' egg ' , ' eggs 2 ' , ' eggs 3 ' , ' 4 eggs ' , ]

# 3, Advantages: Provincial memory, once produced only one value in memory

 

Guess you like

Origin www.cnblogs.com/wangzengyi/p/12298742.html