-->

What is the best way to check if a tuple has any e

2019-04-19 09:30发布

问题:

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:

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")


回答4:

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))