0

如果元组的元组中没有元组为空,我该如何进行返回 true 的测试?

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

(('t2',), ('t3',), ('t4',), ('t5','t6'))

False在这种情况下返回:

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

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

4

2 回答 2

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
于 2013-11-10T09:49:17.070 回答
2

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

这自然会导致一个同样简单(而且,我认为可读性略高)但完全不同的解决方案:

>>> () not in (('t2',), ('t3',), ('t4',), ('t5', 't6'))
True
>>> () not in (('t2',), (), ('t3',), ('t4',))
False
于 2013-11-10T11:06:45.150 回答