我想知道下面的结果是如何产生 True 的。所有条件都不为 True?
有什么意见吗?
>>> listitem=['a','h','o','t']
>>> valid_compare_diff
['0', '1', '2', '3', '4']
>>> all(x for x in listitem if x in valid_compare_diff)
True
新变化:-
>>> listitem=['0']
>>> valid_compare_diff
['0', '1', '2', '3', '4']
>>> all(x for x in listitem if x in valid_compare_diff)
True
当列表理解产生结果时,为什么结果仍然是 True..??
最佳答案
理解将为空,因为 x
的值不满足条件:
如果 x 在 valid_compare_diff 中
因此:
>>> [x for x in listitem if x in valid_compare_diff]
[]
结果为 []
,当传递给 all
时返回 True
>>> all([])
True
之所以如此,是因为 all
的定义指出,如果传递给它的 iterable 为空,则它返回 True
:
all(...)
all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
关于Python all() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16651310/