为什么不能写成这个形式
print filter(lambda s: s if len(s.strip())>0, ['test', None, '', 'str', ' ', 'END'])
或者为什么不能直接写成
print filter(lambda s: len(s.strip())>0, ['test', None, '', 'str', ' ', 'END'])
print filter(lambda s: s if len(s.strip())>0, ['test', None, '', 'str', ' ', 'END'])
或者为什么不能直接写成
print filter(lambda s: len(s.strip())>0, ['test', None, '', 'str', ' ', 'END'])
举报
filter()函数接受一个函数f和一个list,此函数f()的返回值必须是布尔值True或False,不能是其他类型。
第一种写法lambda s: s if len(s.strip())>0返回的是s,不是bool,所以不对(而且也缺少else情况的返回);
第二种虽然匿名函数返回的是布尔值,但空值None不能再做删除strip,所以错在list中的None碰到strip()函数会报错(AttributeError: 'NoneType' object has no attribute 'strip')
if else缺一不可
因为
函数的返回值是s and len(s.strip())>0
表示返回值应该有s和len(s.strip())>0这两个
而匿名函数也应该返回两个值