为什么“返回s和s.strip()”在使用过滤器时有效? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

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
python list filter short-circuiting
2个回答
4
投票

将你的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(包括空字符串''),0False0.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']

1
投票

首先让我们做一些基本的调试。

"A" and "A".strip()在外壳上打印“A”

现在为什么这样做。那么让我们来看看and的工作原理

see here

“如果A and BA返回A is False,否则返回B

所以,由于"A"不是0Falsenot_empty将返回"A".strip()。现在"A".strip()=="A",所以not_empty返回"A"

类似地,当调用filter时,它将应用函数并检查结果,除非剥离列表为空,否则它将不会获得False。因此,它会给你['A','B','C']。

© www.soinside.com 2019 - 2024. All rights reserved.