为何不能用if 必须用 and,是不是filter的原因?
print filter(lambda s: s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])
print filter(lambda s: s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])
2016-11-24
>>> print filter(lambda x:x and len(x.strip())>0,['a',' ','b','','c']) ['a', 'b', 'c'] >>> print filter(lambda x:x if len(x.strip())>0,['a',' ','b','','c']) File "<stdin>", line 1 print filter(lambda x:x if len(x.strip())>0,['a',' ','b','','c']) ^ SyntaxError: invalid syntax >>> a=lambda s:-s if s<0 File "<stdin>", line 1 a=lambda s:-s if s<0 ^ SyntaxError: invalid syntax >>> a=lambda s:-s if s<0 else s >>> a(-4) 4 >>> print filter(lambda x:x if len(x.strip())>0 else x,['a',' ','b','','c']) ['a', ' ', 'b', 'c']
==============
同样的问题,搜了半天,自己做了如上测试,只能帮到这了。原理不明白。
举报