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


分支测试(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-目录

 



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

转载于:https://my.oschina.net/u/2325575/blog/519636

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值