python: 参数2维列出size是否满足我的要求

python: Parametered 2 dimentional list's size weather it meets my requirment or not

我想检查一下传递过来的二维表是否符合我的要求

def foo(twoDList):
 if len(twoDList) == 2:
   if len(twoDList[]) == 3:
     print("true")

然后在使用方法时:

a = [[1, 2, 3], [4, 5, 6]]
foo(a)  

应该是真的!我该如何修复

的 foo()

len(twoDList) == 2 and all(len(sublist) == 3 for sublist in twoDList)

len(twoDList[]) 给我一个语法错误,因为你必须在方括号之间传递一个索引。

我假设您希望每个子列表都恰好包含三个元素:

def foo(twoDList):
    if len(twoDList) == 2:
        if all(len(sublist) == 3 for sublist in twoDList):
            print("true")

如果要在 twoDList 不符合要求时引发错误,请使用 assert 关键字:

def foo(twoDList):
    assert(len(twoDList) == 2 and all(len(sublist) == 3 for sublist in twoDList))
    print("true")