Python 在元组的元组中建立空元组
如果元组的元组中没有一个元组是空的,那么如何执行返回true的测试 例如,在本例中,返回Python 在元组的元组中建立空元组,python,python-3.x,Python,Python 3.x,如果元组的元组中没有一个元组是空的,那么如何执行返回true的测试 例如,在本例中,返回True: (('t2',), ('t3',), ('t4',), ('t5','t6')) (('t2',), (), ('t3',), ('t4',)) 在这种情况下,返回False: (('t2',), ('t3',), ('t4',), ('t5','t6')) (('t2',), (), ('t3',), ('t4',)) 请给出您的答案,以便它对Python3有效。您可以使用内置的all函
True
:
(('t2',), ('t3',), ('t4',), ('t5','t6'))
(('t2',), (), ('t3',), ('t4',))
在这种情况下,返回False
:
(('t2',), ('t3',), ('t4',), ('t5','t6'))
(('t2',), (), ('t3',), ('t4',))
请给出您的答案,以便它对Python3有效。您可以使用内置的
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
您可以使用内置的
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
“一个元组中没有一个元组是空的”的对立面是“某个元组…是空的”;等价地,“可以在元组的元组中找到一个空元组”
这自然会产生一个同样简单(我认为,可读性稍高)但完全不同的解决方案:
>>> () not in (('t2',), ('t3',), ('t4',), ('t5', 't6'))
True
>>> () not in (('t2',), (), ('t3',), ('t4',))
False
“一个元组中没有一个元组是空的”的对立面是“某个元组…是空的”;等价地,“可以在元组的元组中找到一个空元组”
这自然会产生一个同样简单(我认为,可读性稍高)但完全不同的解决方案:
>>> () not in (('t2',), ('t3',), ('t4',), ('t5', 't6'))
True
>>> () not in (('t2',), (), ('t3',), ('t4',))
False