为什么 “return s and s.strip()” 在用 filter 去掉空白字符时好使?


如题:

给定一个数组,其中该数组中的每个元素都为字符串,删除该数组中的空白字符串。

_list = ["A", "", "", "B", "", "C", "", "", "D", "", ' ']

根据廖大文章,答案是这样的:
def not_empty(s): return s and s.strip() print(list(filter(not_empty, _list)))
 

结果:

['A', 'B', 'C']

 

Why does “return s and s.strip()” work when using filter?

 

用filter()来过滤元素,如果s是None,s.strip()会报错,但s and s.strip()不会报错

>>> _list = ["A", "", "", "B", "", "C", "", "", "D", "", ' ',None]
>>> def not_empty(s):
... return s and s.strip()
...
>>> print(list(filter(not_empty, _list)))
['A', 'B', 'C', 'D']

 


>>> def not_empty(s):
... return s.strip()
...
>>> print(list(filter(not_empty, _list)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in not_empty
AttributeError: 'NoneType' object has no attribute 'strip'

 

 

 

涉及的知识点:

1. filter原理:

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。

此函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数

然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 格式:filter(function, iterable)

2. python的and 返回值

>>> 'a' and 'b'
'b'
>>> '' and 'b'
''
>>> 'b' and ''
''
>>> 'a' and 'b' and 'c'
'c'
>>> '' and None and 'c'
''

在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。

如果布尔上下文中的某个值为假,则 and 返回第一个假值

3. strip()方法作用

去掉字符串前、后空白字符 (即空格)

>>> print(" j d s fk ".strip()) j d s fk

 




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM