Skip to main content
 首页 » 编程设计

Python检查所有空列表中的条件

2025年05月04日11zdz8207

这是正常行为吗?

answer=all(c=='false True answer?' for c in []) 
# answer = True 

如果我想在空列表的“全部”检查值上使用 False 来使用这样的行,可以吗?:

answer=all(set([c=='a' for c in []]) or [False,]) 

看起来不错,如果:

answer=all(set([c=='a' for c in ['a','a']]) or [False,]) 
answer=all(set([c=='a' for c in ['a','b']]) or [False,]) 

我决定使用反向逻辑,例如:

bad_answer=bool([c for c in ['a','b'] if c!='a']) 

请您参考如下方法:

In [2]: all([]) 
Out[2]: True 

是的。

c == '...' 永远不会被评估,因为 for c in [] 不接受任何项目。当 for c in iterable 中的 iterable 为空时,列表理解立即计算为 []。