`
李灵晖-raylee
  • 浏览: 127072 次
博客专栏
Group-logo
从头认识java
浏览量:0
文章分类
社区版块
存档分类
最新评论

零基础学python-19.2 列表解析与序列映射函数map(2)增加分支测试与嵌套循环

阅读更多
这一章节我们继续来深入讨论一下python的列表解析与map,这一次我们增加了分支测试与嵌套循环,下面让我们来看看一些例子:
分支测试(if)


场景1:选出列表里面的偶数

第一种我们使用函数的形式来实现

>>> aList=[1,2,3,4,5]
>>> def test(aList):
    res=[]
    for x in range(len(aList)):
        if aList[x]%2==0:
            res.append(aList[x])
    return res


>>> test(aList)
[2, 4]
>>> 


2.第二种我们采用filter

>>> list(filter(lambda x:x%2==0,[1,2,3,4,5]))
[2, 4]
>>> 


3.第三种使用列表解析实现

>>> [x for x in [1,2,3,4,5] if x %2==0]
[2, 4]
>>> 


场景2:选出列表里面的偶数,然后加1


第一种我们使用函数的形式来实现

>>> aList=[1,2,3,4,5]
>>> def test(aList):
    res=[]
    for x in range(len(aList)):
        if aList[x]%2==0:
            aList[x]+=1
            res.append(aList[x])
    return res




>>> test(aList)
[3, 5]


2.第二种我们采用filter、map和lambda表达式联合实现

>>> aList=[1,2,3,4,5]
>>> list(map(lambda x :x+1,filter(lambda x:x%2==0,aList)))
[3, 5]
>>> 


3.第三种使用列表解析实现

>>> [x+1 for x in [1,2,3,4,5] if x %2==0]
[3, 5]
>>>


嵌套循环


for循环嵌套在列表解析里面

>>> [x+y for x in range(4) for y in range(2)]
[0, 1, 1, 2, 2, 3, 3, 4]
>>> [(x,y) for x in range(4) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
>>> 


等价for循环代码

>>> def test():
    res=[]
    for x in range(4):  
        for y in range(2):
            res.append(x+y)
    return res


>>> test()
[0, 1, 1, 2, 2, 3, 3, 4]
>>> 


>>> def test():
    res=[]
    for x in range(4):  
        for y in range(2):
            res.append((x,y))
    return res


>>> test()
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
>>> 


我们上面是两个序列解析,它还可以增强到N个序列解析,形成N*N的矩阵
综合运用分支测试和嵌套循环来解析列表


下面我们举出一些例子:

>>> [(x,y) for x in range(4) if x%2==0 for y in range(5) if y%2!=0]
[(0, 1), (0, 3), (2, 1), (2, 3)]
>>> 


等级代码

>>> def test():
    res=[]
    for x in range(4):
        if x%2==0:
            for y in range(5):
                if y%2!=0:
                    res.append((x,y))
    return res


>>> test()
[(0, 1), (0, 3), (2, 1), (2, 3)]
>>> 



总结:这一章节主要介绍了增加分支测试与嵌套循环来解析列表。


这一章节就说到这里,谢谢大家

------------------------------------------------------------------

点击跳转零基础学python-目录



版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics