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

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

>>> 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)]

>>>

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

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

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

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

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2015-09-23 14:17

浏览 267

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值