在元组元组中建立空元组

时间:2013-11-10 09:43:11

标签: python python-3.x

如果元组元组中没有元组为空,我怎么能做一个返回true的测试?

例如,在这种情况下返回True

(('t2',), ('t3',), ('t4',), ('t5','t6'))
在这种情况下

返回False

(('t2',), (), ('t3',), ('t4',))

请给出答案,使其对Python3有效。

2 个答案:

答案 0 :(得分:4)

您可以使用内置的all函数,因为Python中的空元组是假的:

Help on built-in function all in module builtins:

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.



>>> all((('t2',), ('t3',), ('t4',), ('t5', 't6')))
True
>>> all((('t2',), (), ('t3',), ('t4',)))
False

答案 1 :(得分:2)

“元组元组中没有元组是空的”的反义词是“有些元组......是空的”;等价地说,“在元组的元组中可以找到一个空元组”。

这自然会导致同样简单(并且,我认为,稍微更具可读性)但完全不同的解决方案:

>>> () not in (('t2',), ('t3',), ('t4',), ('t5', 't6'))
True
>>> () not in (('t2',), (), ('t3',), ('t4',))
False