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"不是真的,为什么会出现结果?
以及为什么
not_empty("(">
'' 也是假的。
>>>' ' is True False >>>' ' is False False
将你的filter
函数转换为一个好的 ol'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
。
您应该知道,所有空可迭代对象(包括空字符串''
(、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 is False
,A and B
返回A
,否则B
">
所以既然"A"
不是0
也不是False
,not_empty
会返回"A".strip()
。 现在"A".strip()=="A"
, 所以not_empty
返回"A"
同样,当调用filter
时,它将应用函数并检查结果,除非剥离列表为空,否则它不会得到False
。 因此,它会给你['A','B','C']。