python 面试题: 列表表达式

[process() for item1 in iterable1 if condition1 for item2 in iterable2 if condition2 For item3 in iterable3 if condition3]


等效于:
res = []
for item1 in iterable1:
    if condition1:
    for item2 in iterable2:
        if condition2:
            for item3 in iterable3:
                if condition3:
                    res.append(Process())

return res                                    

 

>>> L = [18, 'ABC',20,'Yliu','liu']
>>> [[s.lower(), s.upper()] for s in L if isinstance(s, str)]
[['abc', 'ABC'], ['yliu', 'YLIU'], ['liu', 'LIU']]
>>>

Res =[]
for s in L:
    if isinstance(s, str):
        A = [s.lower(), s.upper()]
        Res.append(A)
Return Res        
[x if x > 0 else -x for x in L]
相当于:
Res = []
For x in L:
    A = x if x >0 else -x
    Res.append(A)

Return Res

 

posted @ 2018-02-04 18:32  liuzhipenglove  阅读(243)  评论(0编辑  收藏  举报