验证输入是列表还是单数列表的列表

Validating that input is either list or list of lists of singular elemenents

是否有任何快速验证列表是否采用这种格式的方法:

[a,b,c,...]
or
[[a,b,c...],[x,e,w,...],...]

但不是

[[[a],[b],[c]...],[[x],[e],[w],...],...]

或类似的东西

[[a,b,[e],f...],[x,e,w,...],...]

本质上要么是单个元素的列表,要么是包含单个元素的列表的列表,但不是列表的列表或更多嵌套的列表..

我试过用类似的东西检查第二种情况:

all(isinstance(elem, list) for elem in v)

但这对我来说行不通

合并 not any()all()or:

flat = lambda l: not any(isinstance(e, list) for e in l)
if flat(v) or all(isinstance(e, list) and flat(e) for e in v):

仅当 none 中的元素 v 是列表或 all 其中是平面列表。

演示:

>>> def flat_or_singular(v):
...     flat = lambda l: not any(isinstance(e, list) for e in l)
...     return flat(v) or all(isinstance(e, list) and flat(e) for e in v)
... 
>>> tests = [
...     ['a', 'b', 'c'],
...     [['a' ,'b', 'c'], ['x', 'e', 'w']],
...     [[['a'], ['b'], ['c']], [['x'], ['e'], ['w']]],
...     [['a', 'b', ['e'], 'f'], ['x', 'e', 'w']],
... ]
>>> for test in tests:
...     print('{}: {}'.format(flat_or_singular(test), test))
... 
True: ['a', 'b', 'c']
True: [['a', 'b', 'c'], ['x', 'e', 'w']]
False: [[['a'], ['b'], ['c']], [['x'], ['e'], ['w']]]
False: [['a', 'b', ['e'], 'f'], ['x', 'e', 'w']]