为了账号安全,请及时绑定邮箱和手机立即绑定

为什么lambda s后用【 s and len(s.strip())>0 】可以而 【 (len(s.strip())>0) and s 】不行

print filter( lambda s: s and len(s.strip())>0 ,['test', None, '', 'str', '  ', 'END']) #运行正确

print filter( lambda s: (len(s.strip())>0) and s ,['test', None, '', 'str', '  ', 'END'])#运行错误


正在回答

3 回答

因为none无法用strip,就是为了避免none被strip报错,所以才先s,none先判断false ,and后面就不会执行了。

取巧的用法,这么写相当于免了你去判断s是不是none,以及是none之后的后处理

2 回复 有任何疑惑可以回复我~

短路效应

0 回复 有任何疑惑可以回复我~
AttributeError: 'NoneType' object has no attribute 'strip',报的这个错, None没有strip这个属性,这是字符串的属性,放前面可以先排除掉None


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255533    人
  • 解答问题       3038    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

为什么lambda s后用【 s and len(s.strip())>0 】可以而 【 (len(s.strip())>0) and s 】不行

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号