问题
Can anyone help me understand why the following Python script returns True
?
x = ''
y = all(i == ' ' for i in x)
print(y)
I imagine it's something to do with x
being a zero-length entity, but cannot fully comprehend.
回答1:
all()
always returns True
unless there is an element in the sequence that is False
.
Your loop produces 0 items, so True
is returned.
This is documented:
Return
True
if all elements of the iterable are true (or if the iterable is empty).
Emphasis mine.
Similarly, any() will always return False
, unless an element in the sequence is True
, so for empty sequences, any()
returns the default:
>>> any(True for _ in '')
False
回答2:
As the documentation states, what all
does is:
Return True if all elements of the iterable are true (or if the iterable is empty).
来源:https://stackoverflow.com/questions/19257821/python-all-function-with-conditional-generator-expression-returning-true-why