如題:
給定一個數組,其中該數組中的每個元素都為字符串,刪除該數組中的空白字符串。
_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
