What is the best way to check if a tuple has any empty/None values in Python?

南楼画角 提交于 2019-12-09 14:06:09

问题


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?

For example:

t1 = (1, 2, 'abc')
t2 = ('', 2, 3)
t3 = (0.0, 3, 5)
t4 = (4, 3, None)

Checking these tuples, every tuple except t1, should return True, meaning there is so called empty value.

P.S. there is this question: Test if tuple contains only None values with Python, but is it only about None values


回答1:


It's very easy:

not all(t1)

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.




回答2:


An answer using all has been provided:

not all(t1)

However in a case like t3, this will return True, because one of the values is 0:

t3 = (0.0, 3, 5)

The 'all' built-in keyword checks if all values of a given iterable are values that evaluate to a negative boolean (False). 0, 0.0, '' and None all evaluate to False.

If you only want to test for None (as the title of the question suggests), this works:

any(map(lambda x: x is None, t3))

This returns True if any of the elements of t3 is None, or False if none of them are.




回答3:


If by any chance want to check if there is an empty value in a tuple containing tuples like these:

t1 = (('', ''), ('', ''))
t2 = ((0.0, 0.0), (0.0, 0.0))
t3 = ((None, None), (None, None))

you can use this:

not all(map(lambda x: all(x), t1))

Otherwise if you want to know if there is at least one positive value, then use this:

any(map(lambda x: any(x), t1))



回答4:


For your specific case, you can use all() function , it checks all the values of a list are true or false, please note in python None , empty string and 0 are considered false.

So -

>>> t1 = (1, 2, 'abc')
>>> t2 = ('', 2, 3)
>>> t3 = (0.0, 3, 5)
>>> t4 = (4, 3, None)
>>> all(t1)
True
>>> all(t2)
False
>>> all(t3)
False
>>> all(t4)
False
>>> if '':
...     print("Hello")
...
>>> if 0:
...     print("Hello")


来源:https://stackoverflow.com/questions/31154372/what-is-the-best-way-to-check-if-a-tuple-has-any-empty-none-values-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!