这个问题在这里已有答案:
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# result: ['A', 'B', 'C']
我不知道为什么会这样。我知道:x和y如果x为假,则为x,否则为y。首先是返回'A'和'A'.strip()。但这表现在python IDLE中
>>>'A' is True False >>>'A' is False False
所以。 not_empty('A')返回'A',对吧? 'A'不是真的,为什么结果呢?
为什么呢
不是空的(' ') “”
''也是假的。
>>>' ' is True False >>>' ' is False False
将你的filter
函数转换为一个好的'for
循环:
old = ['A', '', 'B', None, 'C', ' ']
new = []
for i in old:
if i and i.strip():
new.append(i)
print(new)
输出:
['A', 'B', 'C']
为什么会发生这种情况是因为if
评估了表达式的真实性。
你应该知道所有空的iterables(包括空字符串''
),0
,False
和0.0
都在表达式中被评估为False
。有一些空格字符串,当被剥离时,被缩减为空字符串,也被评估为False
。
遍历每个元素,这是您的程序运行方式:
Initial
old = ['A', '', 'B', None, 'C', ' ']
new = []
Iteration 1
i = 'A'
'A' and 'A'.strip() is evaluated to True
new = ['A']
Iteration 2
i = ''
'' is evaluated to False (short circuit)
new = ['A']
Iteration 3 (same as 1)
i = 'B'
...
new = ['A', 'B']
Iteration 4
i = None
None is evaluated to False
new = ['A', 'B']
Iteration 5 (same as 1, 3)
i = 'C'
...
new = ['A', 'B', 'C']
Iteration 6
i = ' '
' ' is True but ' '.strip() is False
new = ['A', 'B', 'C']
Final
new = ['A', 'B', 'C']
首先让我们做一些基本的调试。
"A" and "A".strip()
在外壳上打印“A”
现在为什么这样做。那么让我们来看看and
的工作原理
“如果A and B
,A
返回A is False
,否则返回B
”
所以,由于"A"
不是0
或False
,not_empty
将返回"A".strip()
。现在"A".strip()=="A"
,所以not_empty
返回"A"
类似地,当调用filter
时,它将应用函数并检查结果,除非剥离列表为空,否则它将不会获得False
。因此,它会给你['A','B','C']。