在 python 中断言二维列表

Assert 2-d list in python

在 python 中,我正在尝试检查给定列表是否为二维列表。我应该使用 assert 语句,但我不知道如何创建。

到目前为止我有

assert type(x) == list

我知道这是不正确的并检查一维列表。我该如何解决这个问题?

检查 x 是否是您已经做过的列表

assert type(x) == list

检查 x 是否为列表以及 x 的元素是否为列表 -

assert type(x)==list
assert reduce(lambda a,b : type (b) == list and a, x, True)

检查 x 是否为列表以及 x 的元素是否为列表且每个元素的长度相同 -

assert type(x)==list
assert reduce(lambda a, b: type (b) == list and a, x, True)
l = len(x[0])
assert reduce(lambda a, b: len(b) == l and a, x, True)

您可以使用 all 而不是 reduce,这会使其更具可读性。

检查 x 是否为列表以及 x 的元素是否为列表且每个元素的长度相同 -

assert type(x)==list
assert all([type(i) == list for i in x])
l = len(x[0])
assert all([len(i) == l for i in x])

我这样做了...

l=[[]] assert type(l) == list and type(l[0]) == list

但是对于一维情况我得到了一个 indexError 所以我改用它...

l=[]
try:
    assert type(l) == list and type(l[0]) == list
except IndexError:
        assert False

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AssertionError

也许有更好的方法,但对我来说不是很明显。

一个更好的(但冗长的)方法可能是...

 assert type(l) == list and len({ type(el) for el in l }) == 1 and { type(el) for el in l }.pop() == list