mlczhg 发表于 2017-5-8 11:33:28

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

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

分支测试(if)



场景1:选出列表里面的偶数
  第一种我们使用函数的形式来实现

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

>>> test(aList)

>>>



  2.第二种我们采用filter

>>> list(filter(lambda x:x%2==0,))

>>>



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

>>> if x %2==0]

>>>




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


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

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


>>> test(aList)




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

>>> aList=
>>> list(map(lambda x :x+1,filter(lambda x:x%2==0,aList)))

>>>



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

>>> if x %2==0]



>>>



嵌套循环


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

>>>

>>> [(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()

>>>

>>> 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-目录




  


版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: 零基础学python-19.2 列表解析与序列映射函数map(2)增加分支测试与嵌套循环