zoukankan      html  css  js  c++  java
  • 零基础学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-目录

     



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

  • 相关阅读:
    CentOS 7搭建vsftp服务
    Istio
    Kubernetes
    Kubernetes
    Kubernetes
    Kubernetes
    Kubernetes
    Kubernetes
    Kubernetes
    11.树的抽象数据类型和几种表示法
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896719.html
Copyright © 2011-2022 走看看