检查元组在 Python 中是否有任何空/无值的最佳方法是什么? [英] What is the best way to check if a tuple has any empty/None values in Python?
问题描述
检查所有元组值的最佳/最有效方法是什么?我是否需要遍历所有元组项并进行检查,还是有更好的方法?
What is the best/most efficient way to check if all tuple values? Do I need to iterate over all tuple items and check or is there some even better way?
例如:
t1 = (1, 2, 'abc')
t2 = ('', 2, 3)
t3 = (0.0, 3, 5)
t4 = (4, 3, None)
检查这些元组,除了t1
之外的每个元组都应该返回True,这意味着存在所谓的空值.
Checking these tuples, every tuple except t1
, should return True, meaning there is so called empty value.
附言有这个问题:用 Python 测试元组是否只包含 None 值,但它只是关于 None 值
P.S. there is this question: Test if tuple contains only None values with Python, but is it only about None values
推荐答案
很简单:
not all(t1)
仅当 t1
中的所有值都为非空/非零且不是 None
时才返回 False
.all
短路,所以它只需要检查直到第一个空的元素,这使得它非常快.
returns False
only if all values in t1
are non-empty/nonzero and not None
. all
short-circuits, so it only has to check the elements up to the first empty one, which makes it very fast.
这篇关于检查元组在 Python 中是否有任何空/无值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!